1

How do you pass nice error messages to clients in express?

app.use(errorHandler);

function errorHandler(err, req, res, next) {
  res.send(err);
}

app.post('/login', usernameIsValid, pwdIsValid, createToken);

In usernameIsValid I create a new Error with a message and status and call next(err). Now this bypasses pwdIsValid and createToken like it should BUT the weird thing is my errorHandler logs the error without a console.log. Am I using the default error handler in express somewhere? How do I turn it off? I have tried both production and development for NODE_ENV.

On the client xhr.responseText is my error.message + what looks like a stack trace? I've even tried just to send err.message but it looks the same.

One way to handle this mess is to make each middleware (if there is an error) create an error string like req.data.err = "invalid username" and then make sure each following middleware checks req.data.err if the string is present. But this is tedious as hell >_<

2 Answers 2

0

I solved it. You need to apply the error handler app.use(errorHandler) dead last after all other routes. This disables the built-in error handler. Now you may pass pretty error messages to the client.

Read more here.

edit: process.env.NODE_ENV does not matter.

-1

From the express documentation site

If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.

So if you want to avoid the stacktrace you only need to execute your application with the NODE_ENV set to production.

Run you application as follows:

$ NODE_ENV=production node file.js
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.