I am trying to intelligently handle the success/error responses from our API using fetch & ES6 promises.
Here is how I need to handle response statuses:
I think you can write it out pretty easily:
fetch(…).then(response => {
if (response.ok)
return response[response.status == 204 ? "text" : "json"]();
if (response.status == 422)
return response.json().then(err => { throw err; });
if (response.status == 406)
var error = new AuthentificationError(response.statusText); // or whatever
else
var error = new Error(response.statusText)
error.response = response
throw error;
})
Following on from Bergi's solution, you might consider mechanising the handling of responses with a fairly simple ResponseHandler()
object;
function ResponseHandler() {
this.handlers = [];
this.handlers[0] = function() {}; // a "do nothing" default handler
}
ResponseHandler.prototype.add = function(code, handler) {
this.handlers[code] = handler;
};
ResponseHandler.prototype.handle = function(response) {
var h = this.handlers,
s = response.status,
series = Math.floor(s / 100) * 100; // 100, 200, 300 etc
(h[s] || h[series] || h[0])(response); // sniff down the line for a specific/series/default handler, then execute it.
};
In use :
// create an instance of ResponseHandler() and add some handlers :
var responseHandler = new ResponseHandler();
responseHandler.add(204, function(response) {...}); // specific handler
responseHandler.add(422, function(response) {...}); // specific handler
responseHandler.add(406, function(response) {...}); // specific handler
responseHandler.add(200, function(response) {...}); // 200 series default handler
responseHandler.add(400, function(response) {...}); // 400 series default handler
responseHandler.add(0, function(response) {...}); // your overall default handler
// then :
fetch(…).then(response => { responseHandler.handle(response); });
You would lose the efficiencies of a hard coded solution such as Bergi's, but potentially benefit from improved manageability and reusability.