如何使用 ecmascript-6 获取自定义服务器端错误消息并获取 api? [英] How to get custom server-side error message with ecmascript-6 and fetch api?
问题描述
当客户端获取请求导致服务器端出现错误时,我想返回错误代码 (400) 和自定义消息.我不知道如何在客户端优雅地使用 fetch 和 Promise 检索两者.
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 字符串,因为这是您在第一个 中的 onFulfill 回调中返回的内容.then()代码>.更好的方法是返回一个
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);
});
这篇关于如何使用 ecmascript-6 获取自定义服务器端错误消息并获取 api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!