I'm developing a Express + PostgreSQL app and I want to implement a global error handler system. Now I want to caught all uncaught exceptions from my entire project. Server is running with nodemon
.
A code like this console.log(x)
should give a custom error that I created because x is not defined;
I'm putting process.on('uncaughtException', () => {})
in my server.js
file, located in root directory and inserting error with console.log(x)
in app.js
that is also in root directory folder.
Here is my server.js
code:
import './src/config/dotenv.js';
import app from './app.js';
process.on('uncaughtException', (err) => {
console.log(err.name, err.message);
console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...');
process.exit(1);
});
const port = 3000;
const server = app.listen(port, () => {
console.log(`Server running on port ${port}...`);
});
process.on('unhandledRejection', (err) => {
console.log(err.name, err.message);
console.log('UNHANDLED REJECTION! 💥 Shutting down...');
server.close(() => {
process.exit(1);
});
});
This is what I tried:
- I already tried to put uncaughtException handler on top, before all imports, but that's not working;
- And problem I also not in
nodemon
; - I don't have any others uncaughtExceptions handlers in other files;
console.log(x)
error is not located in asynchronous code, I understand that this handler only caught synchronous code;