Created
February 15, 2017 21:12
-
-
Save remy/6cd4504d0b10adfb3d1adb291bef12fb 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 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