Why does an uncaught exception crash a Node.js server? It's common in asynchronous callbacks and functions that have no exception handling. During the process, the async callback is pushed to the event queue and gets executed. If it doesn't have any try/catch surrounding an exception, it's on its call stack. If an error is thrown in this case, it will be moved to the top of the event loop tick. As the error is unhandled in an async context, Node considers the app to be unstable and terminates the process with a non-zero error code. Node.js takes this decision because, as the event loop is single-threaded, there is no higher context to return from. And continuing might lead to unknown issues. So, it is better to terminate the process. Even if calling a function is wrapped with try/catch, it won't help, as that operates in a different call stack. However, Node.js emits a special event, uncaughtException, which can be used to log the reason. Cheers! #nodejs #backend #javascript #server
Great explanation, Ali. One subtle point I’d add is that it’s not just about async callbacks, an uncaught exception in any context will crash the process because it escapes the current call stack entirely. Also, the idea of the error being “moved to the top of the event loop tick” can be a bit misleading. It’s more accurate to say the error bubbles up within its own execution context, and once it reaches the event loop boundary without being handled, Node has no safe recovery path. That’s why relying on uncaughtException isn’t a real solution..it’s useful for logging, but the process should still exit to avoid running in a potentially inconsistent state.
Node.js didn’t crash… it rage quit after seeing that unhandled error.
Nice breakdown!