What is a good pattern for reporting errors when misusing directives for reuse in Angular?

What is a good template for reporting errors when writing directives for reuse in Angular?

I am writing several components as angular directives for the purpose of reusing them, expecting developers to join this project later and not have all the information that I have now about using this directive.

I document the directive and code for its use, and I have unit tests, which are mostly examples of proper use for additional “documentation”. I still want meaningful answers / exceptions to be returned to the developer when they build the pages with the directive.

Is there a general exception throwing pattern, or perhaps a log entry that is used to help report the misuse of the directive for developers involved in working with it?

+4
source share
3 answers

Although this is probably a more general JS question than Angular, the same theories still apply. You should wrap things in try / catch / finally blocks and throw errors if necessary.

function Blah(isRequired, isOptional){
    var X = 7, Y = 0;
    try{
        Y = X * isRequired;
    }
    catch(err){
        throw new Error('You must provide a value for "isRequired"');
    }
    finally{
        //this example has none, but do cleanup things here
    }
}

If you want to show the log, you can use the Angular shell to write to the console. This will prevent errors when using IE and try to write to console.debug by writing them instead of console.log.

Setup:

myapp.config(['$logProvider', function($logProvider){
    $logProvider.debugEnabled(true);
})
.run(['$rootScope', '$log',
    function ($rootScope, $log) {
        'use strict';

        //create a reference to $log on the root scope
    $rootScope.$log = $log;
    }]);

Using:

$scope.$log.log(message);
$scope.$log.debug(message);
$scope.$log.info(message);
$scope.$log.warn(message);
$scope.$log.error(message);

/ , . - .

<div data-log-enabled my-directive>
</div>

:

link: function(scope, element, attributes){
    if(attributes.logEnabled){
        scope.$log.debug('blah');
    }
}

, , , , .

+2

:

console.log()

console.debug()

console.info()

console.warn()

console.error()

enter image description here

,

0

: "" angularjs?

Angular uses an exception / error throwing pattern when directives have missing attributes or are used incorrectly, etc.

0
source

Source: https://habr.com/ru/post/1539030/


All Articles