Catch error inside express route

291
July 28, 2017, at 07:48 AM

I have a node.js service that is being called from a main application. I've had issues where an error occurs in the service and the service hangs preventing any other requests from being handled. I have code to catch errors in common places like after doing a mongodb query.

model.aggregate(
    [
     ...
    ],function (err, result) {
        if (err) {
            next(err);
        }
        else {
        //other code
        }

I am also catching uncaught exceptions and killing the service in this case with the following code.

process.on('uncaughtException', function (er) {
    console.error(er.stack);
    logger.log('info','Cbt Dev Service crashed',er);
    process.exit(1);
});

These seem to be working fine except I occasionally run into issues where an error occurs but isn't caught by either. An exmple of an error in this case is after getting a result from a mongodb query and getting an error like "Cannot read property 'subjectAreas' of undefined. This error seems to get caught by the mongodb middleware. The code looks like this.

function (err, result) {
if (err) {
    res.send(errorHandler(err, req));
}
else {
    var subjectAreas = result[0].subjectAreas.sort();
}

In this case result is an empty array so obviously throws an error. I understand that I can prevent this with better written code like using try/catch but if I'm not aware this issue exists and the service hangs up again, I don't know what the error is in order to fix it so that's why I need to log it.

Is there something else I can do that will catch these kinds of errors?

Rent Charter Buses Company
READ ALSO
Issues with nodemailer. Works locally but not deployed

Issues with nodemailer. Works locally but not deployed

i just switch my website from a static to a node app in order to use stripeSo i am working with nodemailer

317
NodeJS development on iPad [on hold]

NodeJS development on iPad [on hold]

I am developing NodeJS by using my Mac and host my projects on Heroku most of the times

298
Webpack dynamic require gives Mixed Content error

Webpack dynamic require gives Mixed Content error

I am trying out Webpacks dynamic require which turns whatever I require into a dynamic module and splits off the code

422
Webpack requires files dynamically

Webpack requires files dynamically

I am trying to require files dynamically with Webpack like so:

410