Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When developing a library, should we throw errors/exceptions?

I'm developing a pub/sub Mediator library to be used by others and I don't know how to handle errors.

Here's an example piece of code:

/**
 *
 * @param String channel Channel to subscribe
 * @param String|function callback Function name or callback
 * @param String context Context to bind function to
 * @param Boolean once True to subscribe once
 **/
this.subscribe = function (channel, callback, context, once) {

    if (!_.isObject(context)) {
         context = window;
    }

    if (!_.isFunction(subscription) && !_.isFunction(context[subscription])) {
        throw new Error('Function passed as callback to channel subscription named  ' + channel + ' seems invalid!');
    }

    // Everything ok, add to channels object
    channels[channel].push({fn: subscription, context: context || this, once: once});
}

This method is part of the library. It's API expects a channel name and a valid callback (either the function name, a lambda or a callback).

If the channel argument is not a string, the library readily stop. If an invalid context is passed, window is assumed. Mistakes in both these parameters are easily debugaable.

However, if an invalid callback is passed, it propagates the error until an event is fired (a channel publishing is made). In a pub/sub system this might become a nightmare to debug if, for instance, the event is rarely fired.


So my question is...

In this specific scenario, taking in account that I'm developing a javascript library to others, should I:

  • throw Errors to prevent further error propagation?
  • return false/undefined/-1 and not register the subscription?
  • proceed as normal at let it die somewhere, leaving the debugging to the third party developer

NOTE: There's a similar question but my situation is a bit different and the answers provided didn't put my spirit at ease.

like image 243
Tivie Avatar asked Feb 07 '13 15:02

Tivie


1 Answers

I guess this answer is more of my opinion and what I follow. You have to ask yourself if you should return throw an error and let the consumer, of your library, handle the error. If the error is something that cannot be recovered from, there is no need for you to throw an error (in JS). Your library should be able to fallback gracefully to alternatives but if it cannot do that for a certain function, it should return undefined. Most JS developers do check for undefined and it's a pretty common practice to do so while using library functions. Returning false is usually done in event handlers if an event cannot be handled.

like image 177
praneetloke Avatar answered Oct 04 '22 20:10

praneetloke