Reputation: 28611
I'm using Sails.js to develop a REST API server.
For ease of use and for abstraction sake I would like to throw exceptions inside of my controllers, e.g.:
// api/controllers/TempController.js
module.exports = {
index: function(request, response) {
throw new NotFoundException('Specific user is not found.');
throw new AccessDeniedException('You have no permissions to access this resource.');
throw new SomeOtherException('Something went wrong.');
}
};
How do I catch those exceptions automatically (on a global level) and transform them into a valid JSON response? e.g.:
{
"success": false,
"exception": {
"type": "NotFoundException",
"message": "Specific user is not found."
}
}
Is it the best possible approach to use built-in serverError
response in order to handle such exceptions? Or is it better to create some custom middleware? If so, could you provide a simple example?
Upvotes: 2
Views: 1985
Reputation: 28611
The unhandled exceptions are passed to the default response in the api/responses/serverError.js
as a first argument data
.
Here's an example of how such exceptions can be handled:
var Exception = require('../exceptions/Exception.js');
module.exports = function serverError (data, options) {
var request = this.req;
var response = this.res;
var sails = request._sails;
// Logging error to the console.
if (data !== undefined) {
sails.log.error('Sending 500 ("Server Error") response: \n', String(data));
} else {
sails.log.error('Sending empty 500 ("Server Error") response');
}
response.status(500);
if (data instanceof Exception) {
return response.json({
success: false,
exception: {
type: data.constructor.name,
message: data.message
}
});
} else {
return response.json(data);
}
};
When exception is thrown in the controller:
// api/controllers/TempController.js
var NotFoundException = require('../exceptions/NotFoundException.js');
module.exports = {
index: function(request, response) {
throw new NotFoundException('Specific user is not found.');
}
};
This will output the following JSON:
{
"success": false,
"exception": {
"type": "NotFoundException",
"message": "Specific user is not found."
}
}
Upvotes: 2