Search code examples
node.jserror-handlingloopbackjsstrongloop

Execute code on error


I want to execute a code of automated mail whenever there is any kind of error from any of the API.

Though this is possible to write that code in catch block of a remote method but my code base is too long and hence this is not a best fit. Another issue with this is approach is for API which are not custom remote method and are generated by loopback, it is hard to use catch block with them.

Can someone help me with an easy approach where I need to write code once and the end result will be whenever there is an error in any of my API my code for mail runs automatically.


Solution

  • Got the answer after struggling for a day.

    Loopback provides RemoteHook (afterRemoteError) for a model-method,

    _modelName_.afterRemoteError( _methodName_, function( ctx, next) {
    //...
    next();
    });
    

    So whenever a particular method returns any error this block of code is executed.

    Read more about remote hooks : https://loopback.io/doc/en/lb2/Remote-hooks.html

    To make this block of code run every time any method returns error, we can use wildcards

    _modelName_.afterRemoteError(** , function( ctx, next) {
    //...
    next();
    });
    

    Read more about wildcards here : https://loopback.io/doc/en/lb2/Remote-hooks.html#wildcards