如何使用ecmascript-6和fetch api获取定制的服务器端错误消息?

如何使用ecmascript-6和fetch api获取定制的服务器端错误消息?

问题描述:

当客户端提取请求导致服务器端发生错误时,我想返回错误代码(400)和自定义消息。我不知道如何在客户端优先使用提取和承诺来检索。

When a client-side fetch request results in an error on the server side, I'd like to return an error code (400) and a custom message. I don't know how to retrieve both on the client-side elegantly using fetch and promises.

return fetch('/api/something')
    .then(response => response.json())
    .then(json => {
         console.log(json.message)
        // I only have access to the json here.
        // I'd also like to get the response status code 
        // (from the response object) and potentially 
        // throw an error complete with the custom message.
    })
    .catch(function(ex) {
        console.log('Unhandled Error! ', ex);
    });

谢谢!

您只能访问JSON字符串,因为这是您第一个 .then()中的 onFulfill 回调所返回的内容>。一个更好的方法是返回一个 Promise.all()包装器,它解析为具有原始响应对象以及已解决JSON对象的数组:

You only have access to the JSON string since that is what you returned from the onFulfill callback in your first .then(). A better approach would be to return a Promise.all() wrapper that resolves to an array with the original response object as well as the "resolved" JSON object:

return fetch('/api/something')
    .then(response => Promise.all([response, response.json()]))
    .then(([response, json]) => {
        if (response.status < 200 || response.status >= 300) {
            var error = new Error(json.message);
            error.response = response;
            throw error;
        }
        // Either continue "successful" processing:
        console.log('success!', json.message);
        // or return the message to seperate the processing for a followup .then()
        // return json.message;
    })
    .catch(function(ex) {
        console.log('Unhandled Error! ', ex);
    });