에러 처리

Younghwan Cha·2022년 12월 1일
0

cleanCode

목록 보기
2/7

발생한 error 를 확인하기 위해서 아래와 같은 코드를 작성했다

try {
	...
} catch(e) {
	console.log('[ERROR]' + e)
}

이정도면 나중에 error 가 발생했을 때 원인을 파악하고 대응하는 데 문제가 없다고 생각했다.
하지만 error 가 발생하고 보니까 [ERROR] InvalidInputError: Value list must have at least 1 member.
...무슨 error 가 발생했는지 유추는 가능했지만 정확히 어디서 무엇 때문에 error 가 발생했는지 알 수 없었다.

위 상황을 간단한 예시를 통해서 다시 보자면,
console.log('error' + e) 와 같이 에러를 출력하게되면 앞의 'error' 가 string 이기 때문에 이에 따라
Error 객체인 e 또한 toString 처리 되어 error message 인 test error 만 출력되게 된다.
때에 따라서 error message 만 출력하는 것으로 충분할 수도 있지만,
대부분의 경우 error 가 발생한 부분을 확인하고 문제가 있다면 고쳐야 하기 때문에 어디에서 최대한 자세한 정보를
받는 것이 중요하다.
따라서, console.log('error', e) 와 같이 출력하게 되면 e 객체에 대한 자세한 정보가 출력됨을 알 수 있다.

이러한 작은 차이라도 error 를 확인하고 관리하는데 큰 차이를 만들 수 있기 때문에 신경써서 개선해보도록 하자.

const e = new Error('test error')

> console.log('error' + e)
	errorError: test error

> console.log('error', e)
error Error: test error
    at REPL1:1:11
    at Script.runInThisContext (node:vm:129:12)
    at REPLServer.defaultEval (node:repl:572:29)
    at bound (node:domain:433:15)
    at REPLServer.runBound [as eval] (node:domain:444:12)
    at REPLServer.onLine (node:repl:902:10)
    at REPLServer.emit (node:events:525:35)
    at REPLServer.emit (node:domain:489:12)
    at REPLServer.Interface._onLine (node:readline:491:10)
    at REPLServer.Interface._line (node:readline:868:8)
profile
개발 기록

0개의 댓글