Cleanest way to handle custom errors with fetch & ES6 promise

我是研究僧i 提交于 2019-11-30 09:24:42
Bergi

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;
})
Roamer-1888

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!