grunt-mocha-test throwing errors that I expect to be caught in my try/catch block


I am performing rest api validation using grunt-mocha-test (test written in coffeescript). The client i'm using to call the api will throw a custom defined error if the response is anything other than a 200. In some cases, such a response simply means the database isn't ready with the data that I am validating, so I want to poll the service until either it is ready or I timeout. Since an error is thrown each time it's not ready (i.e. not 200), I want to wrap my calls in a try/catch block -- retrying in the catch block. Unfortunately, mocha throws my error instead of allowing my catch block to catch it.

Below is an example of my code:

Client = require 'rest-client'
client = new Client

describe "Try catch test", ->
  it 'should catch my error', (done) ->
    retry = (done) ->  
          client.mightThrowAnError, (response) ->
      catch error
        retry done

    retry done

Of course, in practice I have code in the catch block that eventually errors out after a number of retries so I don't recursively call retry forever, but I've omitted that here for simplicity, since mocha throws the error instead of ever allowing my catch block to handle it:

Uncaught Error: <my custom Error>

Is this a bug/design limitation with Mocha or am I doing something wrong?

[EDIT: The error thrown is a custom Error defined in my rest client]

Problem courtesy of: Clandestine


I'm going to suggest a possibility. client.mightThrowAnError is doing something asynchronously. (Seems obvious.) If it is the asynchronous part of what client.mightThrowAnError which raises an error, this this will happen outside the try...catch block and will not be caught.

Solution courtesy of: Louis


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.