Skip to content

Instantly share code, notes, and snippets.

@kawanet
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save kawanet/8930806 to your computer and use it in GitHub Desktop.

Select an option

Save kawanet/8930806 to your computer and use it in GitHub Desktop.
An Express.js middleware wraps error responses as JSON structure.
/**
* @example
* var app = express();
* app.use(wrapError);
* app.use(yourMiddleware);
*/
function wrapError(req, res, next) {
var superSend = res.send;
res.send = _send;
next();
function _send(code, err) {
var args = Array.prototype.slice.call(arguments);
if (args.length === 1 && code instanceof Error) {
err = code;
code = 500; // Internal Server Error
}
if (code - 0 > 0 && err instanceof Error) {
err += ""; // stringify
args[1] = {
error: {
message: err
}
}
}
superSend.apply(res, args);
}
}
@kawanet
Copy link
Author

kawanet commented Feb 11, 2014

Express で res.send(new Error("something")) したレスポンスを適当な JSON に変換してくれるミドルウェア。
主に Web API 向けを想定。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment