Reputation: 6973
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:
{}
Upvotes: 1
Views: 1034
Reputation: 29916
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);
});
Upvotes: 3
Reputation: 92
Remove the status 400 like so:
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.json('Error occurred in Apps Api: ' + err);
});
}
Upvotes: -1