NodeJS Custom Error Handler (with stacktrace)

JS
S
JavaScript

Concept from Derick Bailey. Useful way to capture a stack trace after throwing a custom error.

1function createError(msg, status){
2    const err = new Error(msg);
3    err.status = status;
4    Error.captureStackTrace(err,createError);
5    return err;
6}
7
8const err = createError('something went wrong', 500);
9throw err;

Created on 11/3/2017