I am rather new to nodejs so I will explain in a bit more detail what I am trying to do.
I have a webserver. If a request fails I want to log the stack trace of that exception, but deliver a error page and not crash the server.
As an example, the function handling the requests:
var Q = require('q'); var requestHandler = function () { // Here I get the data etc. that was requested. As this is not important, just a dummy here Q.resolve() // Now I answer the request .then(function (data) { // Dummy Code representing the sending of a response console.log('sending response …'); console.log('oh no! an exception'); // Now an Exception occurs throw new Error('You did something wrong!'); }) // If there was any error, show the error page instead .fail(function (err) { // Dummy Code representing the sending of the error page console.log('sending error page'); // Additionally I want to write the error into a log file console.error('You had an error: ', err); }) // If there was an error in the .fail-handler, I deserve the server to crash .done(); }; // A request comes in, I want to call my handler requestHandler();
The console's output:
sending response … oh no! an exception sending error page You had an error: [Error: You did something wrong!]
I can't see a way to access the stack trace. But when I throw an exception in the .fail-handler (or just omit the complete .fail-handler), I get a stack trace on the console (but I'd have to restart the server).
So I guess my question is:
How do I access the stack trace in a promise fail handler?
EDIT: Any tips on how to improve the explanation are welcome, of course. If I didn't make myself clear, please let me know.
Logging the stack traces of runtime exceptions assists developers in diagnosing runtime failures. However, unnecessary logging of exception stack traces can have many negative impacts such as polluting log files.
We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.
Adding the async keyword to a function will turn any exceptions thrown inside that function (or any throw propagated from other functions called within it) into a rejection. The same happens when refactoring callback based code that throws into async functions / Promises.
Errors inside the Promises If you throw an error inside the promise, the catch() method will catch it, not the try/catch. In this example, if any error in the promise1, promise2, or promise4, the catch() method will handle it.
Logging the error object won't print error's stack trace. You need to ask for it specifically:
console.error('You had an error: ', err.stack);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With