1

I'm reading through John Papa's angular style guide and came across this code under the Exception Handling section. Can someone please explain to me where reason comes from or how it works in that code? This is one of those JavaScript/Angular things I just don't get how it works.

/* recommended */
angular
    .module('blocks.exception')
    .factory('exception', exception);

exception.$inject = ['logger'];

function exception(logger) {
    var service = {
        catcher: catcher
    };
    return service;

    function catcher(message) {
        return function(reason) {
            logger.error(message, reason);
        };
    }
}

1 Answer 1

1

The catcher function returns a function itself that has the argument reason. In the code you posted, the function isn't called, therefore there is no reason provided, yet.

Assuming someone has injected exception somewhere else, you could call it like this:

var catcher = exception.catcher('This is a message');
var loggerError = catcher('This is the reason');

Or in a single line:

var loggerError = exception.catcher('This is a message')('This is the reason');
Sign up to request clarification or add additional context in comments.

2 Comments

What is the advantage of doing it that way over function catcher(message, reason)?
You can preconfigure the logger. Think of var log = exception.catcher('Something went wrong') and the reason as the error in an $http.get(...).then(successFn, function (error) { log(error); };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.