Last active
August 29, 2015 13:56
-
-
Save kawanet/8930806 to your computer and use it in GitHub Desktop.
An Express.js middleware wraps error responses as JSON structure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @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); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Express で res.send(new Error("something")) したレスポンスを適当な JSON に変換してくれるミドルウェア。
主に Web API 向けを想定。