어차피 에러가 발생이 된다면 로그에서 확인을 할 수 있을텐데
에러를 catch문이나 에러 핸들러로 해주는 이유는 무엇일까?
서버의 중단을 방지하기 위해서이다.
const condition = false
if (condition) {
console.log('서버 정상 실행 중')
} else {
throw new Error('알 수 없는 에러 발생')
}
// error
// eominkyu@pisimingyuui-MacBookAir codingTest % node code
// /Users/eominkyu/Desktop/codingTest/code.js:7
// throw {message: '알 수 없는 에러 발생'}
// ^
// { message: '알 수 없는 에러 발생' }
// Node.js v18.16.0
위 코드를 실행하게 되면 어플리케이션은 중단이 되고 해당 에러문구가 터미널에서 뜨게 된다.
하지만, try-catch문으로 넣어둔 코드를 보자
const condition = false
try {
if (condition) {
console.log('서버 정상 실행 중')
} else {
// throw new Error('알 수 없는 에러 발생')
throw {message: '알 수 없는 에러 발생'}
}
} catch (err) {
console.log(err)
}
// console
// { message: '알 수 없는 에러 발생' }
이 코드를 보게 된다면 error가 발생이 되었지만 어플리케이션은 중단되지 않고
터미널에서만 출력값이 나오게 된다.