我有以下函數來自mern.io堆棧。使用提取,如何正確處理拒絕
export default function callApi(endpoint, method = 'get', body) {
return fetch(`${API_URL}/${endpoint}`, {
headers: { 'content-type': 'application/json' },
method,
body: JSON.stringify(body),
})
.then(response => response.json().then(json => ({ json, response })))
.then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
.then(
response => response,
error => error
);
}
我調用該函數如下方式
callApi('auth/register', 'post', {
username,
password,
}).then(function(res) {
// do stuff
});
的反應要麼是201或422如何處理422的正確方法?如果用戶名已經存在,則會發生422。
我是否把所有的邏輯在第一然後如下面的:
callApi('auth/register', 'post', {
username,
password,
}).then(function(res) {
if (res.error) {
} else {
}
});
它不拋出一個錯誤,這裏是回購代碼:https://github.com/Hashnode/mern-starter/blob/master/client/util/apiCaller.js – Jose
問題機智h在'callApi'中最後一個'then'是它將任何失敗的承諾變成一個解決的承諾,IMO只是愚蠢的。它應該完全省略 – Phil