什么是我的node.js try / catch最简洁的替代方案?

时间:2016-08-31 16:03:53

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

概述

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

我的问题

我的问题是我无法从上述来源中辨别出 my 特定的try / catch实例是不安全还是可能容易出错,因为在某些情况下try / catch in node。 js是合适的(例如json解析)。我的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"));
}

关闭

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

最佳,

克里斯

1 个答案:

答案 0 :(得分:2)

Your code allows for an error to be thrown when there's no match for a filename (which would make /.../.exec() return null, and null[1] will throw). That's not really an exceptional situation, it's just lazy return value handling :)

I would probably use something like this myself:

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"));
}

It has the added advantage that not all calls to parseFileName (might there be more) are required to use try/catch.