首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ecmascript-6和fetch api获取自定义服务器端错误消息?

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

Stack Overflow用户
提问于 2015-09-10 20:58:16
回答 2查看 1.3K关注 0票数 1

当客户端获取请求导致服务器端出现错误时,我想返回一个错误代码(400)和一条自定义消息。我不知道如何在客户端优雅地使用fetch和promises来检索两者。

代码语言:javascript
复制
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);
    });

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-11 05:57:39

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

代码语言:javascript
复制
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);
    });
票数 5
EN

Stack Overflow用户

发布于 2015-09-10 22:11:46

回答我自己的问题。

编辑.

在Amit和Felix的帮助下,我确定了下面的代码,因为这对我来说是最容易阅读的。

代码语言:javascript
复制
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!');
        }
    });

...End编辑

Promise.all会像这里描述的那样为我工作:How do I access previous promise results in a .then() chain?。然而,我觉得这是不可读的。因此,ES7 async起到了拯救作用!

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32511474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档