JS Promises: Allowing Propagation of Errors - javascript

Background
Let's say that I'm working with NodeJS + Express. I have certain error handlers registered with Express that will take care of all errors that might come up in my application in the appropriate way(s).
As such, I throw errors in my application whenever I need to do so. If there is an unhandled error, I let it propagate until it reaches an error handler. However, while attempting to throw errors while inside of a promise chain, I ran into a problem. Take the following example:
function find() {
// consider this to be a promise from a library such as Bluebird
return new Promise(function (resolve, reject) {
// ... logic ...
});
}
function controller (req, res) {
// ... omitted ...
find().then(function (result)) {
if (result) {
// let 'res' be the Express response object
res.send("It exists!");
} else {
// let SpecificError be a prototypical subclass of Error
throw new SpecificError("Couldn't find it.");
}
}).catch(function (error) {
// throw the error again, so that the error handler can finish
// the job
throw error;
});
}
Whereas I have been expecting the error that I am re-throwing to eventually hit at least the generic error handler, I am instead seeing the requests that I send to my application hang, and the promise library that I am using complain of a Unhandled rejection.
Question
Quite simply, I am wondering how to resolve the fact that I appear to be mishandling the rejection that I am creating by throwing an error in my promise chain.
Edit: for clarification as to what (specifically) the error handler and controller function are, see the comments below.

Assuming you have bound your function with something like
app.get('/', controller);
When Express calls controller, it has yielded 100% control to you. If an exception is thrown synchronously from controller, Express is nice and will also treat that as an error for you. As soon as you invoke any asynchronous code however, it is your responsibility to decide how to handle any errors.
In the case of Express, you have two options:
Since you were passed req and res, you can catch an error and send whatever response you want back to the user.
controller actually has a function signature of function(req, res, next) in Express. This is a very common format.
The next callback expects to be called if you have not written anything in the response yet. If you call next() with no arguments, this tells Express to look keep processing the set of URL handlers that it has, trying to find one that will handle the request, returning a 404 if none are found.
If however, you pass an argument to next like next(err), Express will skip over remaining URL handlers, instead looking for error handlers. Express allows you to register custom handlers, but if none are found, it will return a 500.
So what should you do in your example? You probably want something like
function controller (req, res, next) {
find().then(function (result)) {
if (!result) throw new SpecificError("Couldn't find it.");
res.send("It exists!");
}).catch(next);
}
That means that if any exception is thrown inside of the promise chain, the next function will be called with it, and Express will take over from there.

Promise handlers are "throw safe". That means any exception you throw in any promise handler will be caught automatically and turned into a rejected promise. That is how the specification is written for promises and how they work (except for some versions of jQuery promises, but that's just because they aren't following the spec).
So, if you are getting "Unhandled rejection" from your promise library, that's designed to be a helpful warning to tell you that you had a rejected promise that had no handler for it so the rejection was silently ignored which is usually a coding mistake.
And, in fact in your controller() function, you have exactly that:
function controller (req, res) {
// ... omitted ...
find().then(function (result)) {
if (result) {
// let 'res' be the Express response object
res.send("It exists!");
} else {
// let SpecificError be a prototypical subclass of Error
throw new SpecificError("Couldn't find it.");
}
}).catch(function (error) {
// throw the error again, so that the error handler can finish
// the job
throw error;
});
}
If you get to the line where it says throw new SpecificError, then that will turn the promise into a rejected promise. That will then cause your .catch() handler to get called. In that handler, you throw again which will keep the promise as a rejected promise. So, the original promise that started with find().then(...) will now be a rejected promise. But, there are no more reject handlers and you are not returning the promise from controller(). So, you have an unhandled rejected promise at that point. That is usually a coding mistake.
You have several choices for how to correct this coding mistake:
You can handled the error yourself in the .catch() handler by calling some sort of error handling function that you pass the error to and you pass the res argument to and then don't throw the error.
You can return the promise from your controller() function and Whatever code is calling that function can then handle the rejected promise there.

Related

NestJS blocking new requests after throwing error

I've got a small testing application (a test lab) with an AppControler and an AppService, AppController has a GET endpoint and send requests payload to AppService, which has two async methods.
AppService
async requestTesting (payload): Promise<void> { // This is what's being called from the controller
if(payload) {
await this.validateErrorHandling(payload)
}
console.log('TESTING', payload)
// DO STUFF
}
async validateErrorHandling(payload): Promise<void> {
console.log('DO STUFF')
if(payload && payload.number > 2) { // This is true
throw new Error()
}
}
When requestTesting calls validateErrorHandling, the second method is going to check that condition (if truthy) and shall throw an Error.
I'm used to do this with an exception filter on real use cases, but in this very specific case, whenever I call my Controller's endpoint and that error is thrown on my AppService, the following is shown:
UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "........".
And I'm unable to make any other request through postman until I restart the app.
Postman shows:
Error: connect ECONNREFUSED 127.0.0.1:3000
Now, I'm aware that a try/catch should fix this, but I'm trying to understand why this is stopping my whole application instead of stopping the function execution only, as it never happened to me before, and if I try to throw it anywhere else, it just works.
Now, both methods have a Promise<void> return type, but if validateErrorHandling throws an error, everything should stop and that console.log('TESTING', payload) should not be executed (as if it were business logic).
I'm afraid it's not just me being silly, but I might actually be missing something.
The reason that we throw an error is that we want to tell the front application that something went wrong. In order to achieve this, it's better to throw an HTTP error instead of simply throwing it. So here is the code:
throw new UnprocessableEntityException({
errorCode: UpdateProductErrorStatusEnum.DeviceNotReported,
message: UpdateProductErrorMsgEnum.DeviceNotReported,
});
You have two options. First throw the error in the service itself, second to throw an Error (as you did) and catch it in the controller layer. Each way has its own pros and cons. Throwing in the controller is better because the controller is designed to handle HTTP related stuff, and service is created for only logic stuff. But throwing in the controller makes the controller messy and maybe your code will not be clean.
See here for more info: https://docs.nestjs.com/exception-filters

Uncaught (in promise) undefined when post function fails [duplicate]

Once a promise reject() callback is called, a warning message "Uncaught (in promise)" appears in the Chrome console. I can't wrap my head around the reason behind it, nor how to get rid of it.
var p = new Promise((resolve, reject) => {
setTimeout(() => {
var isItFulfilled = false
isItFulfilled ? resolve('!Resolved') : reject('!Rejected')
}, 1000)
})
p.then(result => console.log(result))
p.catch(error => console.log(error))
Warning:
Edit:
I found out that if the onRejected handler is not explicitly provided to the .then(onResolved, onRejected) method, JS will automatically provide an implicit one. It looks like this: (err) => throw err. The auto generated handler will throw in its turn.
Reference:
If IsCallable(onRejected)` is false, then
Let onRejected be "Thrower".
http://www.ecma-international.org/ecma-262/6.0/index.html#sec-performpromisethen
This happens because you do not attach a catch handler to the promise returned by the first then method, which therefore is without handler for when the promise rejects. You do have one for the promise p in the last line, but not for the chained promise, returned by the then method, in the line before it.
As you correctly added in comments below, when a catch handler is not provided (or it's not a function), the default one will throw the error. Within a promise chain this error can be caught down the line with a catch method callback, but if none is there, the JavaScript engine will deal with the error like with any other uncaught error, and apply the default handler in such circumstances, which results in the output you see in the console.
To avoid this, chain the .catch method to the promise returned by the first then, like this:
p.then( result => console.log('Fulfilled'))
.catch( error => console.log(error) );
Even if you use Promises correctly: p.then(p1).catch(p2) you can still get an uncaught exception if your p2 function eventually throws an exception which you intend to catch using a mechanism like window.onerror. The reason is that the stack has already been unwound by the error handling done in the promise. To fix this, make sure that your error code (called by the reject function) does not throw an exception. It should simply return.
It would be nice if the error handling code could detect that the stack has already been unwound (so your error call doesn't have to have a flag for this case), and if anyone knows how to do this easily I will edit this answer to include that explanation.
This code does not cause the "uncaught in promise" exception:
// Called from top level code;
// implicitly returns a Promise
testRejectCatch = async function() {
// Nested within testRejectCatch;
// simply rejects immediately
let testReject = function() {
return new Promise(function(resolve, reject) {
reject('test the reject');
)};
}
//***********************************************
// testRejectCatch entry.
//***********************************************
try {
await testReject(); // implicitly throws reject exception
catch(error) {
// somecode
}
//***********************************************
// top level code
//***********************************************
try{
testRejectCatch() // Promise implicitly returned,
.catch((error) => { // so we can catch
window.alert('Report error: ' + error);
// must not throw error;
});
}
catch(error) {
// some code
}
Explanation:
First, there's a terminology problem. The term "catch" is
used in two ways: in the try-catches, and in the Promises.
So, it's easy to get confused about a "throw"; is it throwing
to a try's catch or to a Promise's catch?
Answer: the reject in testReject is throwing to the Promise's
implicit catch, at await testReject; and then throwing on to
the .catch at testRejectCatch().
In this context, try-catch is irrelevant and ignored;
the throws have nothing to do with them.
The .catch at testRejectCatch satisfies the requirement
that the original throw must be caught somewhere,
so you do not suffer the "uncaught in Promise..." exception.
The takeaway: throws from Promises are throws to .catch,
not to try-catch; and must be dealt-with in some .catch
Edit:
In the above code, the reject propagates up through the .catches.
If you want, you can convert over to propagating up the try-catches.
At line 17, change the code to:
let bad = '';
await testReject().catch((error) => {bad = error});
if (bad) throw bad;
Now, you've switched over to the try-catch.
I ran into this issue, but without setTimeout().
In case anyone else runs into this: if in the Promise constructor you just call reject() synchronously, then it doesn't matter how many .then() and .catch() handlers you add to the returned Promise, they won't prevent an uncaught promise rejection, because the promise rejection would happen before you
I've solved that problem in my project, it's a large enterprise one. My team is too lazy to write empty catch hundreds of times.
Promise.prototype.then = function (onFulfilled, onRejected) {
return baseThen.call(this, (x: any) => {
if (onFulfilled)
onFulfilled(x);
}, (x: any) => {
if (onRejected)
onRejected(x);
});
};

Calling 'next()' from promises in a middleware causes 'next shouldn't be called more than once'

Recently I changed my code from Express to Restify. I'm honestly not sure if it used to happen before, but I guess it did.
Basically in my middleware I call a promisified method and when it resolves I call next and do other stuff in the next middleware. When it is rejected I also want to call next with no errors in some cases. Otherwise it must call the error middleware passing err to next.
somePromise()
.then(()=>{
next();
})
.catch((err)=>{
if(err.someatt) next();
else next(err)
});
It works fine with the expected results of somePromise. The problem is that next is bound by the then-catch chain. And when an error is thrown in the next middleware it invokes the catch method and calls next again!
I found out that next has an attribute called and when I turn it to false before calling next again I get rid of the the errors. But of course it is an antipattern. And I'm having the same problem in a different middleware that I also used promises (calling next as expected and then calling it again in the catch statement).
Anyone else had a problem like that?
Change your chain to this:
somePromise().then(() => {
next();
}, err => {
// error occurred in somePromise()
if(err.someatt) next();
else next(err);
}).catch(err => {
// error occurred in .then()'s next()
// don't call next() again
});
The optional second argument of .then() acts as a .catch() callback, but is only invoked for errors thrown higher up in the chain, and is not invoked for errors thrown in the adjacent .then() callback.
A very helpful flowchart borrowed from this awesome answer demonstrates the difference between .then(onFulfilled, onRejected) and .then(onFulfilled).catch(onRejected):

Catching unhandled exceptions in Express when using async/await

Regard the following TypeScript code:
app.get('/test_feature', function (req: Request, res: Response) {
throw new Error("This is the bug");
});
app.use(logErrors);
function logErrors (err: Error, req: Request, res: Response, next: NextFunction) {
console.log(err);
mongoDal.log(err.message, err);
next(err);
}
Here, I throw an error in a requests handler, and it fires the logErrors function as expected.
But then, I change my code to consume an async function:
app.get('/test_feature', async function (req: Request, res: Response) {
throw new Error("This is the bug");
await someAsyncFunction();
});
Now, because my function is async, the error somehow gets handled by the default error handler of Express, so my custom error handler doesn't get reached, nor the Node default error handler:
process.on('uncaughtException', function (err: Error) {
try {
console.log(err);
mongoDal.log(err.message, err);
} catch (err) {
}
});
How can I make my 'logErrors' function reached when an error occurs in an async function? I want a generic solution, not to try/catch in every requests handler.
The problem here is that your handler isn't throwing a synchronous exception at all any more. Instead, your handler returns a promise, which gets rejected. Note that this isn't a promise or async/await specific problem, this is a general issue for any express code using callbacks etc too - if you don't handle errors carefully everywhere when writing async code, it's easy to lose them completely.
To handle this in your case, something needs to register itself to catch rejections from the promise that you're returning. There's a few options for that:
Explicitly add a .catch() to all your error handlers, and handle errors yourself, or by calling next(err) to delegate to the normal express error handling.
Create a wrapping function for your handler to do this, and use it everywhere. You could use an existing wrap() function like express-promise-wrap for this.
Extend .get and friends to automatically track rejections in promises returned from handlers. You could do this by hand, but it looks like express-as-promised is a working implementation of this (although I haven't tried it).
It's a little more complicated to set up, but 3 is strongly preferably in my opinion once you've got it in place. With that, you should be able to just write async functions as handlers, they'll all be returning promises under the hood, and your handler code will automatically monitor those promises for any subsequent failure.
StrongLoop have actually got an article looking at this generally in more detail, if you want some further reading: https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/

Why can I not throw inside a Promise.catch handler?

Why can't I just throw an Error inside the catch callback and let the process handle the error as if it were in any other scope?
If I don't do console.log(err) nothing gets printed out and I know nothing about what happened. The process just ends...
Example:
function do1() {
return new Promise(function(resolve, reject) {
throw new Error('do1');
setTimeout(resolve, 1000)
});
}
function do2() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('do2'));
}, 1000)
});
}
do1().then(do2).catch(function(err) {
//console.log(err.stack); // This is the only way to see the stack
throw err; // This does nothing
});
If callbacks get executed in the main thread, why does the Error get swallowed by a black hole?
As others have explained, the "black hole" is because throwing inside a .catch continues the chain with a rejected promise, and you have no more catches, leading to an unterminated chain, which swallows errors (bad!)
Add one more catch to see what's happening:
do1().then(do2).catch(function(err) {
//console.log(err.stack); // This is the only way to see the stack
throw err; // Where does this go?
}).catch(function(err) {
console.log(err.stack); // It goes here!
});
A catch in the middle of a chain is useful when you want the chain to proceed in spite of a failed step, but a re-throw is useful to continue failing after doing things like logging of information or cleanup steps, perhaps even altering which error is thrown.
Trick
To make the error show up as an error in the web console, as you originally intended, I use this trick:
.catch(function(err) { setTimeout(function() { throw err; }); });
Even the line numbers survive, so the link in web console takes me straight to the file and line where the (original) error happened.
Why it works
Any exception in a function called as a promise fulfillment or rejection handler gets automatically converted to a rejection of the promise you're supposed to return. The promise code that calls your function takes care of this.
A function called by setTimeout on the other hand, always runs from JavaScript stable state, i.e. it runs in a new cycle in the JavaScript event loop. Exceptions there aren't caught by anything, and make it to the web console. Since err holds all the information about the error, including the original stack, file and line number, it still gets reported correctly.
Important things to understand here
Both the then and catch functions return new promise objects.
Either throwing or explicitly rejecting, will move the current promise to the rejected state.
Since then and catch return new promise objects, they can be chained.
If you throw or reject inside a promise handler (then or catch), it will be handled in the next rejection handler down the chaining path.
As mentioned by jfriend00, the then and catch handlers are not executed synchronously. When a handler throws, it will come to an end immediately. So, the stack will be unwound and the exception would be lost. That is why throwing an exception rejects the current promise.
In your case, you are rejecting inside do1 by throwing an Error object. Now, the current promise will be in rejected state and the control will be transferred to the next handler, which is then in our case.
Since the then handler doesn't have a rejection handler, the do2 will not be executed at all. You can confirm this by using console.log inside it. Since the current promise doesn't have a rejection handler, it will also be rejected with the rejection value from the previous promise and the control will be transferred to the next handler which is catch.
As catch is a rejection handler, when you do console.log(err.stack); inside it, you are able to see the error stack trace. Now, you are throwing an Error object from it so the promise returned by catch will also be in rejected state.
Since you have not attached any rejection handler to the catch, you are not able to observe the rejection.
You can split the chain and understand this better, like this
var promise = do1().then(do2);
var promise1 = promise.catch(function (err) {
console.log("Promise", promise);
throw err;
});
promise1.catch(function (err) {
console.log("Promise1", promise1);
});
The output you will get will be something like
Promise Promise { <rejected> [Error: do1] }
Promise1 Promise { <rejected> [Error: do1] }
Inside the catch handler 1, you are getting the value of promise object as rejected.
Same way, the promise returned by the catch handler 1, is also rejected with the same error with which the promise was rejected and we are observing it in the second catch handler.
I tried the setTimeout() method detailed above...
.catch(function(err) { setTimeout(function() { throw err; }); });
Annoyingly, I found this to be completely untestable. Because it's throwing an asynchronous error, you can't wrap it inside a try/catch statement, because the catch will have stopped listening by the time error is thrown.
I reverted to just using a listener which worked perfectly and, because it's how JavaScript is meant to be used, was highly testable.
return new Promise((resolve, reject) => {
reject("err");
}).catch(err => {
this.emit("uncaughtException", err);
/* Throw so the promise is still rejected for testing */
throw err;
});
According the spec (see 3.III.d):
d. If calling then throws an exception e,
a. If resolvePromise or rejectPromise have been called, ignore it.
b. Otherwise, reject promise with e as the reason.
That means that if you throw exception in then function, it will be caught and your promise will be rejected. catch don't make a sense here, it is just shortcut to .then(null, function() {})
I guess you want to log unhandled rejections in your code. Most promises libraries fires a unhandledRejection for it. Here is relevant gist with discussion about it.
Yes promises swallow errors, and you can only catch them with .catch, as explained more in detail in other answers. If you are in Node.js and want to reproduce the normal throw behaviour, printing stack trace to console and exit process, you can do
...
throw new Error('My error message');
})
.catch(function (err) {
console.error(err.stack);
process.exit(0);
});
I know this is a bit late, but I came across this thread, and none of the solutions were easy to implement for me, so I came up with my own:
I added a little helper function which returns a promise, like so:
function throw_promise_error (error) {
return new Promise(function (resolve, reject){
reject(error)
})
}
Then, if I have a specific place in any of my promise chain where I want to throw an error (and reject the promise), I simply return from the above function with my constructed error, like so:
}).then(function (input) {
if (input === null) {
let err = {code: 400, reason: 'input provided is null'}
return throw_promise_error(err)
} else {
return noterrorpromise...
}
}).then(...).catch(function (error) {
res.status(error.code).send(error.reason);
})
This way I am in control of throwing extra errors from inside the promise-chain. If you want to also handle 'normal' promise errors, you would expand your catch to treat the 'self-thrown' errors separately.
Hope this helps, it is my first stackoverflow answer!
Listen for unhandled errors:
window.addEventListener('unhandledrejection', e => {
// ...
});
window.addEventListener('error', e => {
// ...
});
If error gets swallowed, use self.report(error):
.catch(error => {
self.reportError(error);
});
https://developer.mozilla.org/en-US/docs/Web/API/reportError

Categories