Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: Throwing error and it's not being caught

I have an API using swagger integrated with express on node.js and a resource defined as below. A swagger error thrown in the check for (!req.params.id), is caught by swagger's default error handler. An error thrown in the callback from the mongoDB delete call is NOT caught, giving me the error below. The error looks like it has to do with the scope/order of the callback function, and as somebody new to node.js I was hoping to get advice on how to do this properly, maintaining asynchronicity. -thanks

events.js:74 throw TypeError('Uncaught, unspecified "error" event.'); ^ TypeError: Uncaught, unspecified "error" event.

exports.remove = {
    'spec' : {
      "collapsed...for...brevity..." : "...",
      "params" : [ {
        "paramType" : "path",
        "name" : "id",
        "collapsed...for...brevity..." : "...",
      }],
      "errorResponses" : [ swe.notFound('id'), swe.invalid('id') ],
      "nickname" : "remove"
    },
    'action' : function(req, res) {

      if (!req.params.id) {
        throw swe.invalid('id');   // THIS ERROR IS CAUGHT
      }

      req.coll.remove({_id : req.coll.id(req.params.id)}, function(e, result) {
        if (e) {
          throw swe.invalid('collection');   // THIS ERROR IS NOT CAUGHT
        }

        res.send({msg : 'success'});
      });
    }
  };
like image 614
rogodeter Avatar asked Nov 14 '13 16:11

rogodeter


People also ask

Can I throw error in catch?

The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.

How do I catch exceptions in node JS?

Exception handling in callback-based( asynchronous) code: In callback-based code, the one of the argument of the callback is err. If an error happens err is the error, if an error doesn't happen then err is null. The err argument can be followed any number of other arguments.

Does throw error Stop Execution JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.


1 Answers

Exceptions thrown within an async callback go to the caller of the callback, not your surrounding code. So it's the req.coll.remove code that receives the exception (which isn't handling it) and that crashes your app.

Instead, you need to have your remove action function accept a callback parameter that it can use to communicate errors back to the caller.

This is why exceptions are rarely used in node.js code and callbacks are the standard.

like image 170
JohnnyHK Avatar answered Sep 29 '22 20:09

JohnnyHK