사가에서는 에러핸들링하는 방법이 2가지 종류가 있다.
일반적으로 아래와 같이 사용한다. 이 방식은 😟😟간단하지만 응답에 에러메세지를 실어보내는 경우 원하는 메세지를 보여주지 않는다.
/**
APIS
*/
const signupApi = (data) => {
return axios.post('/auth/signup', data)
}
/**
REQUESTS
*/
function* signupRequest(action) {
try {
const user = yield call(signupApi, action.data)
yield put({ type: TYPES.SIGNUP_FULFILLED, payload: user.data })
} catch (error) {
if (error) {
console.error(error)
yield put({ type: TYPES.SIGNUP_REJECTED, error })
}
}
}
/**
WATCHERS
*/
function* watchSignupRequest() {
yield takeLatest(TYPES.SIGNUP_REQUEST, signupRequest)
}
위 방식대로 한다면 백엔드에서
res.status(401).json(err)
를 해줄 때 에러에 response가 담겨 있어도 아래 첫번째 사진처럼 status code에 매핑되는 statusMessage를 보여줄뿐 response에 담긴 내용을 보여주지 않는다.
두번째 방법은 조금 더 손이 가지만 🥳🥳원하는 에러메세지를 보일 수 있다.
/**
APIS
*/
const signupApi = (data) => {
return axios
.post('/auth/signup', data)
.then((response) => response)
.catch((error) => error)
}
/**
REQUESTS
*/
function* signupRequest(action) {
const { response, data: successData } = yield call(signupApi, action.data)
if (successData) {
yield put({ type: TYPES.SIGNUP_FULFILLED, payload: successData })
}
if (response) {
const { data } = response
yield put({ type: TYPES.SIGNUP_REJECTED, error: data })
}
}
/**
WATCHERS
*/
function* watchSignupRequest() {
yield takeLatest(TYPES.SIGNUP_REQUEST, signupRequest)
}
원하는 에러메세지를 보일 수 있다.