There's more...

Another useful feature built into jsonapi-serializer is providing JSON API-formatted error responses. We can update our /middleware/rest.js middleware to provide 404 error responses in our REST API that are formatted consistently to align with the JSON API specification.

...
var JSONAPIError = require('jsonapi-serializer').Error;

module.exports = function(resourceId, store, serialize, deserialize) {
var serializer = new JSONAPISerializer(resourceId, serialize);
var deserializer = new JSONAPIDeserializer(deserialize);

var error = function(status, title, description) {
return new JSONAPIError({
status: status,
title: title,
detail: description

});
};

var fileNotFound = function() {

return error(404, 'Not found', 'Resource does not exist.');
}
;
...

return resource({
id : resourceId,

load : function(req, id, callback) {
find(id, function(item) {
if (!item) {
callback(fileNotFound());
} else {
callback(null, item);
}
});
},
...

Now, when our API can't find a resource, it will return the JSON API error response:

{
"errors": [{
"status": 404,
"title": "Not found",
"detail": "Resource does not exist."
}]
}

There are many ways to customize these error responses, including providing error status codes, source pointers to identify request body format issues, and much more.


You can learn more about error handling in JSON API specification and jsonapi-serializer by checking out their official documentations, respectively:
http://jsonapi.org/
https://github.com/SeyZ/jsonapi-serializer
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.169.14