【问题标题】:What is the most terse alternative to my node.js try/catch?我的 node.js try/catch 最简洁的替代方法是什么?
【发布时间】:2023-03-25 13:59:01
【问题描述】:

概述

我有一个 node.js 应用程序,它通过 HTTP 调用外部 API,并对响应标头中返回的 content-disposition 标头值进行正则表达式验证和捕获。我目前将其编码为 try/catch 块;但是,我已经阅读了大量资料,这些资料似乎一般都避开了这种方法。

我的问题

我的问题是,我无法从上述来源中完全辨别 my 特定的 try/catch 实例是否不安全或可能容易出错,因为在某些情况下,node.js 中存在 try/catch 的情况。 js是合适的(例如json解析)。下面显示的 try/catch 块是否有更好的替代方法?

我的 Try/Catch 块

var parseFileName = function (contentDisposition) {
    "use strict";
    return /filename[^;=\n]*=[\\'"]*((['"]).*?\2|[^;'"\n]*)/g.exec(contentDisposition)[1];
};

try {
    contentDisposition = response.headers["content-disposition"];
    fileName = parseFileName(contentDisposition);
} catch (e) {
    console.error(e);
    return next(new Error("Content Disposition parse failed"));
}

关闭

非常感谢您提供任何见解或帮助。

最好的,

克里斯

【问题讨论】:

    标签: node.js error-handling try-catch


    【解决方案1】:

    当文件名不匹配时,您的代码允许抛出错误(这将使/.../.exec() 返回null,而null[1] 将抛出)。这并不是真正的特殊情况,只是懒惰的返回值处理:)

    我自己可能会使用这样的东西:

    let parseFileName = function (contentDisposition) {
      "use strict";
      let match = /filename[^;=\n]*=[\\'"]*((['"]).*?\2|[^;'"\n]*)/g.exec(contentDisposition);
      return match ? match[1] : null;
    };
    
    let contentDisposition = response.headers["content-disposition"];
    let fileName = parseFileName(contentDisposition);
    if (! fileName) {
      return next(new Error("Content Disposition parse failed"));
    }
    

    它还有一个额外的优势,即并非所有对parseFileName 的调用(可能还有更多)都需要使用try/catch

    【讨论】:

    • 啊好吧,这很有道理。我需要阅读有关该主题的更多信息;但是,在这种情况下,您的解决方案对我来说肯定是有意义的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多