当客户端获取请求导致服务器端出现错误时,我想返回一个错误代码(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);
});谢谢!
发布于 2015-09-11 05:57:39
您只能访问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);
});发布于 2015-09-10 22:11:46
回答我自己的问题。
编辑.
在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!');
}
});...End编辑
Promise.all会像这里描述的那样为我工作:How do I access previous promise results in a .then() chain?。然而,我觉得这是不可读的。因此,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);https://stackoverflow.com/questions/32511474
复制相似问题