Chris C Chris C - 1 month ago 5x
Node.js Question

What is the most terse alternative to my node.js try/catch?


I have a node.js app, which calls out to an external API via HTTP and does a regular expression validation and capture on the content-disposition header value returned in the response header. I currently have it coded as a try/catch block; however, I have read ample sources which seem to shun this approach in general.

My Issue

My issue is that I cannot quite discern from said aforementioned sources whether my particular instance of try/catch is unsafe or potentially error prone, as there are some cases in which try/catch in node.js is appropriate (e.g. json parsing). Is there a better alternative to my try/catch block shown below?

My Try/Catch Block

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) {
return next(new Error("Content Disposition parse failed"));


Thanks very much in advance for any insight or help.




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.