如何使用 ecmascript-6 获取自定义服务器端错误消息并获取 api?

How to get custom server-side error message with ecmascript-6 and fetch api?

当客户端获取请求导致服务器端出现错误时,我想 return 一个错误代码 (400) 和一条自定义消息。我不知道如何使用 fetch 和 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);
    });

谢谢!

回答我自己的问题。

编辑...

在 Amit 和 Felix 的帮助下,我选择了下面的代码,因为它对我来说最容易阅读。

async function format(response) {
    const json = await response.json();
    return {response, json};
}

function checkStatus(response, json) {
    if (response.status < 200 || response.status >= 300) {
        var error = new Error(json.message);
        error.response = response;
        throw error;
    }
    return {response, json};
}

return fetch('/api/something')
    .then((response) => format(response))
    .then(({response, json}) => checkStatus(response, json))
    .then(({response, json}) => {
        console.log('Success!', json.message);
    })
    .catch((error) => {
        if (error && error.response) {
            console.log('error message', error.message);
        } else {
            console.log('Unhandled error!');
        }
    });

...结束编辑

Promise.all 会像这里描述的那样对我有用:。但是,我发现那是不可读的。所以 ES7 async 函数来拯救!

async function formatResponse(response) {
    var json = await response.json();
    response.json = json;
    return response;
}

function checkResponseStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    } else {
        var error = new Error(response.json.message);
        error.response = response;
        throw error;
    }
}

function handleResponse(response) {
    console.log('success!', response.json);
}

function handleError(error) {
    if (error && error.response) {
        console.log('error message', error.message);
        console.log('error response code', error.response.status)
    } else {
        console.log('Unhandled error!');
    }
}

return fetch('/api/something')
   .then(formatResponse)
   .then(checkResponseStatus)
   .then(handleResponse)
   .catch(handleError);

您只能访问 JSON 字符串,因为这是您在第一个 .then() 中从 onFulfill 回调中 return 编辑的内容.更好的方法是 return 一个 Promise.all() 包装器,它解析为一个包含原始响应对象以及 "resolved" JSON 对象的数组:

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