I find it difficult to find where the error occured when using next(err). Is there a way how to save the stack to trace the error back to the original files? (Even if it was a validation error I would like to know the exact place from where it originated.)
You can add error.stack to your error handling.
console.log(error, error.stack)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack
Related
is there a node cli option that lets it not print an error?
For example, I'd like the command below not to print an uncaught exception, even if it occurs. But I don't simply want to catch it in the code. If there's no exception or error, then it should print (if message to print exists) what it's intended to.
$ node --quiet-on-err(?) this-script-throws-err.js
Thanks,
This is a good use case for redirection (assuming you're using a platform that has /dev/null): node this-script-throws-err.js 2/>dev/null.
Wouldn't catching all uncaught exception work for you? Add this to the code. This is a process wide event handler that gets called whenever an uncaught exception is found.
process.on('uncaughtException', (exception) => {
// handle or ignore error
});
Is it possible to catch and ignore errors in a Mongoose post-save hook, resulting in a successful return (resp. a resolved promise) from a document save call?
Sample code:
schema.post('save', function postSave(err, doc, next) {
if (err.name === 'MongoError' && err.code === 12345) {
// this does not work the way I'd expect it to
return next();
}
return next(err);
});
The above hook still results in the save call failing with the original error (next(null) doesn't help either). I can replace the error by passing a custom one to next, which shows that the mechanism is generally working, but that doesn't really help me.
The Mongoose middleware docs contain a very similar example (see the "Error Handling Middleware" section near the bottom), but don't really explain the intended behavior of the next callback.
For context, what I'm trying to accomplish in the actual project is a post-save middleware hook that retries the save call when a duplicate key error is encountered.
However, there is a special kind of post middleware called "error handling middleware" that executes specifically when an error occurs. Error handling middleware is useful for reporting errors and making error messages more readable.
I think it is too late in the hooks chain to do this. It would seem that the pre "save" hook would be a good place to check for duplicate keys no? There you can error out and then in your code re-try as you see fit.
The error handling middleware is more of an error formatting mechanism really.
I'm using Nodejs in my windows machine. the question is Nodejs always terminate process on errors e.g. empty Mysql insert statement.
So in production time, and without manual error handling, how can prevent NodeJs exit?
example code:
app.post('/api/accounts',function(req,res){
pool.getConnection(function(error,connection){
connection.query('insert into accounts set ?',req.body,function(err,results){
if (err) {
throw err ;
} else {
console.log(results) ;
}
});
});
console.log('post received') ;
console.log(req.body);
});
Imagine i post an empty req.body.
nodejs will exit on error like this
\node_modules\mysql\lib\protocol\Parser.js:77
throw err; // Rethrow non-MySQL errors
^
Is it possible to configure something in node to just show errors but don't exit?
It's not really a good thing to be continuing execution after a unhandled exception has been thrown by the interpreter (as Ginden said in his answer) - anything could happen and it could prove to be a mistake later, any sort of hole could easily be opened by stopping the process from cleaning up after something went so unexpectedly wrong in your code.
You could sensibly add a event handler for unhandledException like the answer by Ginden points out, however, it seems you're using express and it would make much more sense actually handling the error with middleware when it happens, instead of using throw as per your code.
Replace throw err; with return next(err); and that should mean the request will fall through to the next set of middleware, which should then handle the error, do some logging, tell the user, whatever you want it to do.
app.use(function(err, req, res, next) {
// Maybe log the error for later reference?
// If this is development, maybe show the stack here in this response?
res.status(err.status || 500);
res.send({
'message': err.message
});
});
Don't try to prevent process shutdown. If error was thrown, anything could happen.
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.
Domain module: don't ignore errors.
By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state.
The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.
The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.
To avoid node/ express server crashing, it is always a good idea to catch the errors. As far as I found, there are three ways to record the error:
throw new Error(err);
logger(err);
res,json(500, err);
Should I use all of them to catch an error, if so, what is the invoking order?
Is it possible to avoid crashing if we just throw the error?
Check out this guy link and learn about error handling
https://www.youtube.com/watch?v=p-2fzgfk9AA
His video is very informative and he explains all different types of error handlings
You can use a package connect-domain.
Here is the example.
http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html
Or You can use node.js built in uncaught exception event to handle uncaught errors.
//put this code in your server.js
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
Similar questions has been asked, I went through 'how to debug node' threads, but
those are however either old or not about the problem i got.
Problem:
I'm writing some small tools in node.js stack - and my debugging experience is quite frustrating: when an exception is thrown, in many cases I get very annoying messages like the one here:
TypeError: Bad argument
wtf? it's neither verbose or useful - no source line number, no information in which file this exception was thrown.
Question:
How do I get my console to output usefull information when exceptions/errors are thrown and console.log function has something to say. would be great to have a simple console.log call where it actually puts a line number and maybe a file name where the message happens.
in nodejs i use this function to see error stack:
process.on('uncaughtException', function(err) {
console.log(err.stack);
})
Use the --stack option to see stack traces. Such as grunt task --stack