Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should async function never ever throw?

I wrote a library with a number of async functions. A SYNCHRONOUS helper function throws an error if one of the parameters is plain wrong:

proto.makeParameters= function( filters ){
  default:
    throw( new Error("Field type unknown: " + fieldObject.type ) );
  break;
}

In my async functions, when I use it, I have:

proto.someAsyncFunction = function( cb ){

  // Run the query
  try {
    var parameters = this.makeParameters( filters );
  } catch( e ){
   return cb( e );
  }
}

So:

  • Is it good practice that asyncfunctions should never ever throw? (Like I did)

  • Right now, I am catching ALL errors. Shall I e more choosy? Maybe make up an error type and just check for that? If so, what should I do in either case?

like image 345
Merc Avatar asked Oct 03 '22 11:10

Merc


2 Answers

Your assumptions on the async code are correct. See this post by Isaac Schlueter himself on the topic:

The pattern in node is that sync methods throw, and async methods pass the error as the first argument to the callback. If the first argument to your callback is falsey (usually null or undefined), then all is well with the world.

http://groups.google.com/forum/#!msg/nodejs/W9UVJCKcJ7Q/rzseRbourCUJ

like image 159
Hector Correa Avatar answered Oct 13 '22 11:10

Hector Correa


Is it good practice that async functions should never ever throw? (Like I did)

async functions, of course, will throw exceptions whenever we like it not, simply because of the software imperfection. So throwing custom exception is completely fine but what is important is how to correctly catch them.

The problem is that differently from sync code the stack of the async exception may not be available. So when the exception occurs, it is not always possible to say where to return the control and where is the handler. node.js has two methods of specifying what to do when the exception in asynchronous code occurs: process uncaughtException and domains.

As you see, dealing of the exceptions in async code is tricky so throwing an exception should be considered as a last option. If the function just returns status of the operation it is not an exception.

It seems for me that in the provided code fragment the exception is thrown correctly because it indicates that the method was called improperly and cannot do its job. In other words, the error is permanent. This indicates serious flaw in the application that should be fixed. But if the function cannot create a parameter for some temporary reason that can be fixed without modifying the application, then returning the status is more appropriate choice.

like image 34
Alex Netkachov Avatar answered Oct 13 '22 11:10

Alex Netkachov