6

My node.js (Express.js) application crashes every time an error occurs (syntax, undefined variable, etc.).

Is there any solution to just log it and not crash my app? I read node.js Error's documentation but can't find a solution. https://nodejs.org/api/errors.html

I generated application from express generator. I'm talking about this, here is syntax error, variable is undefined but server is running: http://prnt.sc/e2b7ce it's not crashed

earl-95
  • 133
  • 3
  • 11
Vatex Official
  • 239
  • 3
  • 4
  • 12
  • The engine in my car doesn't work. Is there any way to just drive it whilst taking note of the errors? – Craicerjack Jan 30 '17 at 17:09
  • 1
    @Craicerjack this is right but in your case :)) – Vatex Official Jan 30 '17 at 17:14
  • what is `asfa` and why is it just written into your route? `router.get('/', function(req, res, next) { asfa res.render('index', {title: 'Express'}); });`, The `asfa` that is contained in this route isnt defined – Craicerjack Jan 30 '17 at 17:20
  • @Craicerjack I wrote "asfa" to crashed app but it still working. my app is crashing if I wrote something like this – Vatex Official Jan 30 '17 at 17:26
  • 1
    @Craicerjack You can always push the car by hand, if you are strong enough. Solution by Julian works for me. – TomoMiha Nov 05 '19 at 14:36

3 Answers3

4

You could catch the error, but you should not do this with errors that are your fault, because it is in an unpredictible state after such an error its the best to restart the whole app (nodemon, forever). Errors like not reaching the db, validation, errors in promises, ... you should catch it.

To your second question, you can use the event for unhandled errors like that

process.on('uncaughtException', err => {})
Julian
  • 2,724
  • 1
  • 15
  • 21
3

I fixed this problem. When variable is undefined (error)

I inserted this code at last of application's main app.js file (response.error is my custom function for custom message)

app.use(function(err, req, res, next) {
    res.status(err.status || 500).json(response.error(err.status || 500));
});
Vatex Official
  • 239
  • 3
  • 4
  • 12
1

It depends on the error but the answer most of the time is no. If the error is crashing your app, chances are its something the app needs to run. If youre talking about specific errors you would need to share details of those errors.
This might be a good read regarding error handling in node
Node.js Best Practice Exception Handling

Community
  • 1
  • 1
Craicerjack
  • 6,203
  • 2
  • 31
  • 39