Thursday, 8 June 2017

Nested Promise is not propagating error to parent Promise in Node.js?

I'm creating an API using Node.js/TypeScript running Express. Below is an excerpt from my get method. An error is being triggered in the format method, which throws an error that is caught by the promise, but not propagated to the parent promise after a throw:

            this.getModel(objectName).findAll(queryParameters).then(function(databaseObjects) {
                for (let databaseObject of databaseObjects) {
                    var jsonObject = {};
                    //console.log("Database object: ");
                    //console.log(databaseObject);
                    transform.baseFormat(databaseObject, jsonObject)
                    .then(() => transform.format(databaseObject, jsonObject))
                    .then(() => {
                        res.locals.retval.addData(jsonObject);
                    }).catch((e) => {
                        console.log("Caught error during format of existing object: ");
                        console.log(e);
                        throw e;
                    });
                }
            })
            .then(() => {
                if (metadata) {
                    this.metadata(objectName, false, transform, res.locals.retval);

                    delete queryParameters.limit;
                    delete queryParameters.offset;
                    console.log("RUNNING METADATA COUNT: ");
                    this.getModel(objectName).count(queryParameters).then(function(count) {
                        res.locals.retval.setMetadata("records", count);
                        return next();
                    }).catch(function(e) {
                        this.error(e, res);
                        return next();
                    });
                } else {
                    console.log("NO METADATA");
                    return next();
                }
            }).catch((e) => {
                // TODO: Move status into error() function
                console.log("500 Error on GET");
                console.error(e);
                res.locals.retval.addError(ErrorCode.InternalError, e);
                res.status(ErrorCode.InternalError).send(res.locals.retval);
                return next();
            });

Here's the output:

Caught error during format of existing object: 
Test Error

Then the request fails to finish and doesn't return a payload or a status code.

I've read a lot on Promises and I haven't been able to find an issue/solution similar to mine.



via NobleUplift

No comments:

Post a Comment