Is there any alternative to PHP error_reporting(0)
in nodejs? I want to prevent app from closing after an error, I tried the try and catch method
, but it doesn't work.
So, how can I prevent node.js server
from closing after an error ?
Asked
Active
Viewed 3,943 times
3
2 Answers
5
Edit: There is an event for uncaught errors:
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
See duplicate: Make node.js not exit on error
You could also use pm2
to run your script, pm2
will automatically restart your script on crash.
You need to catch the error. For example
try {
error();
} catch(err) {
// do nothing
}
There is no other way as far as i know. So you could fix or catch these errors only.

Jannis Lehmann
- 1,428
- 3
- 17
- 31
-
1I don't have to fix errors, it's beacause I have a mysql module and It closes if the user/pass is incorrect, so I want to prevent this – Jan 16 '16 at 11:58
3
After i review source code of node, I found there is a beautiful method to implement "ctrl+c" existing.
Create file block.js, content is:
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const block = (data) => {
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err)
})
rl.on('SIGINT', () => {
console.log(data)
rl.pause()
})
}
module.exports = {
block
}
Then require this js file in whatever main js file, and run this:
const { block } = require('./block.js')
block('Your exiting message!')
// your other js code after here
// ...
The block.js file would catch err and "ctrl+c" SIGINT exit.

fouvy
- 31
- 1