![](/img/trans.png)
[英]AxiosError : Failed to load resource: net::ERR_CONNECTION_REFUSED
[英]redux-saga catch Failed to load resource: net::ERR_CONNECTION_REFUSED
我使用axios
撥打后端服務器的電話。 借助redux-saga
我可以輕松控制服務器的副作用。
import {call, put, takeEvery} from "redux-saga/effects";
import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_USERNAME_PASSWORD} from "../../constants";
import axios from "axios/index";
const shootApiTokenAuth = (values) => {
const {username, password} = values;
return axios.post(`${ROOT_URL}/api-token-auth/`,
{username, password});
};
function* shootAPI(action) {
try {
const res = yield call(shootApiTokenAuth, action.payload);
const {history} = action.payload;
yield put({
type: REQUEST_SUCCESS,
payload: res
});
history.push('/companies'); //push user to `/companies` page
} catch (err) {
yield put({
type: REQUEST_FAILED,
payload: err
});
}
}
export function* watchSubmitBtn() {
yield takeEvery(SUBMIT_USERNAME_PASSWORD, shootAPI);
}
問題:后端服務器關閉時。 它不會向我返回任何錯誤。 並且瀏覽器將引發錯誤Failed to load resource: net::ERR_CONNECTION_REFUSED
我已經看到了有關回調方法的先前答案,但我更喜歡axios
和redux-saga
不callback
我嘗試過console.log(err)
。 而且我仍在搜索它們以獲取錯誤消息並將其與服務器響應錯誤區分開的方法。
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
題:
如何使用axios
和redux-saga
捕獲err
?
如果將try / catch放在axios請求本身周圍,則可以更詳細地了解原因。
https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253
您可能希望擁有一個自定義錯誤格式和一個錯誤減少程序,以處理各種不同類型的錯誤。 例如,如果收到響應,則可以將其解析並將其添加到錯誤中,否則您將知道將使用“糟糕”頁面或類似內容來處理應用程序級錯誤。
case REQUEST_FAILED:
//Probably it can failed by 2 reason
//1. 404 from server
//2. network is down
if (action.payload.response === undefined) {
return {
token: undefined,
message: 'Network is down',
isAuthenticated: false,
statusCode: 406
}
} else {
const tmp = action.payload.response.request.response;
const tmp2 = JSON.parse(tmp);
return {
token: undefined,
message: tmp2.non_field_errors[0],
isAuthenticated: false,
statusCode: action.payload.response.status
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.