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

Ric*_*lly 0 fetch ecmascript-6 es6-promise

当客户端提取请求导致服务器端出错时,我想返回错误代码(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);
    });
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ami*_*mit 5

您只能访问JSON字符串,因为这是您在第一次使用onFulfill回调时返回的内容.then().更好的方法是返回一个Promise.all()包装器,该包装器解析为具有原始响应对象的数组以及"已解析"的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);
    });
Run Code Online (Sandbox Code Playgroud)