-
Notifications
You must be signed in to change notification settings - Fork 2
Description
const postAPI = async () => {
const res = await axios.post('...')
return res;
}
const handler = async () => {
const res = await postAPI();
setter(res);
}
위와 같은 로직에서
try-catch를 어디에 작성을 해주어야 하는지 고민이 들었다.
const postAPI = async (handleError) => {
try{
const res = await axios.post('...')
return res;
}catch(e){
handleError(e);
}
}
const handler = async () => {
const res = await postAPI();
setter(res);
}
이렇게 요청하는 함수에서 error를 바로 잡아 주어야할지,
const postAPI = async () => {
const res = await axios.post('...')
return res;
}
const handler = async () => {
try{
const res = await postAPI();
setter(res);
}catch(e){
handlerError(e);
}
}
handler에 try-catch를 해주어야할지 고민을 했었다.
처음에는, postAPI에 try-catch를 적용하여 postAPI를 사용하는 여러 handler에서 try-catch를 작성하지 않아도 되도록 하는게 좋지 않을까?
생각을 햇었고,
에러를 발생하자마자 잡아낼수 있어서 좋다고 생각했다.
하지만, postAPI에 try-catch를 적용하면 catch에서 inital Value를 return해주어야한다.
그래야 handler에서 또다른 에러가 발생하지 않는다.
이러한 번거로움도 존재한다고 생각하고,
handler에서 하나의 postAPI 함수를 사용하는게 아니라, 여러 함수들을 사용할 것이다.
그러한 함수 하나하나에 try-catch를 적용하여 catch에 inital value를 반환하는것보다,
handler함수에서 한번에 try-catch를 사용하여 error를 잡아주는게 좋을 것 같다.
굳이 error가 발생했는데 catch로직에서 inital value를 반환해주어 함수가 동작하게 만드는것은 좋지 않아보인다.
수정
결국 두군데 다 try-catch를 두어 Error를 동일시 판정하지 않기로 했다.
handler에만 try-catch를 사용할 경우
const clickUpdateButton: MouseEventHandler = async () => {
try {
const value = teamUpdateDataValidation({ teamNameRef, teamInfoRef, locSelected, teamInfoState, userInfoState });
changeTeamInfo(value)
.then((res) => {
setTeamInfoState((prev) => ({ ...prev, ...res }));
resetInput();
})
.catch((e) => setErrorValue({ errorStr: "팀 정보 수정에 실패했습니다.", timeOut: 1000 }));
} catch (e) {
setErrorValue({ errorStr: e as string, timeOut: 1000 });
}
};
와 같이 api 관련 error를 따로 catch해 주게 되었다.
즉, catch로직이 이중으로 분리가 되었는데,
try-catch를 2번 사용한다면
const clickUpdateButton: MouseEventHandler = async () => {
try {
const value = teamUpdateDataValidation({ teamNameRef, teamInfoRef, locSelected, teamInfoState, userInfoState });
const res = await changeTeamInfo(value);
setTeamInfoState((prev) => ({ ...prev, ...res }));
resetInput();
} catch (e) {
setErrorValue({ errorStr: e as string, timeOut: 1000 });
}
};
으로 한번의 catch로직으로 해결이 가능하다.