프로그램에는 예상치 못한 에러가 있을 수 있다.
Client 쪽의 인터넷이 연결 불가 상태이거나, 서버 쪽의 상태 문제일 수도 있는데
이런 경우에도 웹 서비스는 작동해야하기 때문에 예외 처리는 필수이다.
가장 흔한 예외처리 문법으로는 try~catch~finally가 있는데,
이 post에서는 fetch 함수를 기준으로 catch와 finally의 사용을 서술한다.
catch는 사전적으로 '잡다'라는 의미를 가진다. 즉, 에러가 발생했을 때 catch 안의 내용이 발생하는 것이다.
fetch('url')
.then((res) => res.json())
.then((result) => {console.log(result);})
.catch((error) =>{
console.log(error);
})
위의 코드에서 url 접속시 promise가 fulfilled 상태이면 정상적으로 response와 result가 수행될 것이다.
만약 그렇지 않고, fetch나 각 then 메서드 중 에러가 발생하면 catch 함수가 실행된다.
catch는 promise chaining의 맨 마지막에 두자.
중간에 어떠한 에러가 발생하던 이유를 불문하고 catch가 실행되어야 한다.
상기 사항을 활용해서 이러한 코드도 작성할 수 있다.
fetch('url')
.then((res) => res.json())
.then((result) => {console.log(result);})
.catch((error) =>{
console.log(error);
throw new Error('text');
})
.then(() =>
const member = res;
return member;
)
.then((member) =>
fetch('url',
{
method : 'POST', body: JSON.stringify(member)
}))
.catch((error) =>{
console.log(error);
throw new Error('text');
})
.finally(()=>{ console.log('final behavior'); });
위처럼, 여러개의 catch 문을 통해서 어떠한 순서로 실행되어야하는 작업이 있을 때 필요에 의해 제어할 수 있다.
const loadingVar=true;
fetch('url')
.then((res) => res.json())
.then((result) => {console.log(result);})
.catch((error) =>{
console.log(error);
throw new Error('text');
})
.finally(()=>{ console.log('final behavior'); loadingVar=false; });
finally는 어떠한 경우이든 발생시키는 함수이다.
작업 후 로그를 남긴다거나... 하는 경우에 쓸 수 있다.
또한 웹페이지의 작업 여부를 확인할 수 있는 역할이 가능하다.
이를 통해서 작업이 끝났을 때, 어떠한 의도된 작업을 삽입할 수 있겠다.