Raffaeu Raffaeu - 3 months ago 15
Node.js Question

Node.js Express, Error handling works only with console.error

I am using Node.js Express to create some HTTP REST APIs.
I have methods that call an underline service that returns a Promise as following:

function getAllApps(request, response) {
appService.getAllApps(request.query.$expand).then(function (apps) {
response.status(200).send(apps);
})
}


and I map the method as following:

var api = express.app;
api.get('/apps', getAllApps);


Now, I have introduced error handling as following:

function getAllApps(request, response) {
appService.getApps(request.query.$expand).then(function (apps) {
response.status(200).send(apps);
})
.catch(function (err) {
console.error('Error occurred in Apps Api: ' + err);
response.status(400).send(err);
});
}


Which is working as expected except that when an error is encountered, I get the full error stack in the console as following:

Express is listening on 127.0.0.1:3000
Web Api ready

Error occurred in Apps Api: Error: Actions is not defined on the model.


But my HTTP method return 400 and the body is empty, it contains only the curly brackets:

{}

Answer

It is caused by the error object not having enumerable properties, so JSON.stringify(new Error("my message")) will return {}. To get the same as the console output, you have to coerect the error object to a string, like so:

.catch(function (err) {
  console.error('Error occurred in Apps Api: ' + err);
  response.status(500).send("" + err);
});

PS: you should use status(500) for internal errors.

EDIT

If this case does not need a separate error handling mechanism, you could let express to handle your errors:

function getAllApps(request, response, next) {
  appService.getApps(request.query.$expand).then(function (apps) {
    response.status(200).send(apps);
  })
  .catch(function (err) {
    next(err || new Error("Unknown error"));
  });
}

And if express' default error handling doesn't give you satisfying results, you can register your own error handler:

...

// note that the middleware having 4 parameters makes it an error handler
app.use(function(err, req, res, next) {
  console.error('Error occurred in Apps Api: ' + err);
  response.status(500).send("" + err);
});
Comments