-
-
Save zs-sz/5641bb4f03ee90ceaca59b7f6166fd4c to your computer and use it in GitHub Desktop.
My error handler for express (though, mostly for API handling, since it always talks in JSON)
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
| const codes = require('http-status-codes'); | |
| module.exports = (error, req, res, next) => { // jshint ignore:line | |
| let message = null; | |
| let n; | |
| const { NODE_ENV } = process.env; | |
| if (typeof error === 'number') { | |
| n = error; | |
| error = new Error(codes.getStatusText(error)); | |
| error.code = n; | |
| } | |
| message = error.message || codes.getStatusText(n); | |
| // Ensure we send the correct type of http status, if there's a real error | |
| // then the `error.code` will be a string, override with 500 | |
| // 500, General error: | |
| const status = error.code || 500; | |
| if (typeof status === 'string') { | |
| status = 500; | |
| } | |
| // prepare the error page shown to the user | |
| const e = { | |
| message, | |
| status, | |
| }; | |
| if (status === 401) { | |
| return res.status(status).json({ | |
| status, | |
| message: message + (res.locals.apikey ? ' (wrong api token)' : ''), | |
| }); | |
| } | |
| let msg = `${status} ${req.url} `; | |
| if (req.user) { | |
| msg += `${req.user.username} `; | |
| } | |
| msg += message; | |
| console.error(req.url, msg); // captured in loggly/whathaveyou | |
| res.status(status).json(e); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment