어허

nodejs error, uncaughtException 본문

개발/Node.JS

nodejs error, uncaughtException

AKDK 2018. 1. 10. 11:59
728x90


nodejs 코딩을 하다보면


throw err;


라는 문구를 자주 보게 된다.


보통은 이것을


try {

throw err;

} catch (exception) {

console.log(exception);

}


이렇게 묶어서 프로세스가 죽지 않게 사용한다.


매번 묶어주는것도 보통일은 아닐터


물론, error가 발생했다는것은 프로세스가 죽어야 마땅한 것이고 이 구문에 다시는 오지 않게 코딩을 해야하는것이 맞다


하지만 통신이나 나같은 경우 db에 접근하려하는데 db에 문제가 생겨 접근이 안될때는 err가 발생되기 마련이다


그래서 나온 방안이



process.on('uncaughtException', function (err) {

console.log ('uncaughtException : \n", err);

if (err.code == 'ECONNREFUSED'

|| err.code == 'EHOSTUNREACH') 

{

handler_connect_error (err);

}

else if (err.code == 'ETIMEDOUT')

{

handler_timeout(err);

}

});


이런식으로 잡히지 않은 예외를 몽땅 처리하는 부분을 만들어서 프로세스가 절대 죽지않게 하는 방법이 있었다.


실제로 이렇게 해서 많은 문제들을 해결 할 수 있었다.


찜찜함은 남는다.


해서 찾아봤더니


https://nodejs.org/api/process.html#process_event_uncaughtexception 에 비슷한 내용이 있었다.



Warning: Using 'uncaughtException' correctly#

Note that 'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to On Error Resume Next. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.

Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion.

Attempting to resume normally after an uncaught exception can be similar to pulling out of the power cord when upgrading a computer -- nine out of ten times nothing happens - but the 10th time, the system becomes corrupted.

The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after'uncaughtException'.

To restart a crashed application in a more reliable way, whether uncaughtException is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed.


정리해보면,


uncaughtException 은 최후의 수단일 뿐, 남용해서는 안되며, 어쩔 수 없이 발생했을 경우에는 차라리 프로세스를 죽게 놔두고


다시 재실행 할 수 있는 외부의 감시프로그램을 이용하는 것이 바람직 하다.



단순히 connection error 때마다 프로세스를 죽게 놔두는건 용납되지 않기때문에 일단은 더 명확한 공부가 되기 전까진 위 방법대로 잡아서 처리할 예정이다.


tcp통신을 계속 하는데 상대방 커넥션이 안된다고 계속 죽였다 살릴수는 없지 않는가?



watchdog 을 걸어놓는것은 필수이지만 임베디드의 경우 절대 죽지않아야 하는 것이 당연시 되는데 스크립트형 언어는 어떤게 바람직 한 건지 아직 잘 모르겠다.



728x90
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
공유하기 링크
Comments