Error handling in Angular

1

I have this code for a token , generated with JWT , then I return it to the application if the user accessed it correctly.

var token = $localStorage.token;
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
var tokenObj = JSON.parse(atob(base64));

then validate that the token has the following claim webUserId

if(tokenObj.webUserId){...}

If I replace the value of the token in the localstorage , I expect an error to appear because it is not well-built, but at this point I get an exception:

var tokenObj = JSON.parse(atob(base64));

I get a $exceptionHandler in Angular in the debug console.

How can I control this error so that the angle exception does not come out?

    
asked by AndreFontaine 18.02.2016 в 17:15
source

2 answers

3

To avoid the error you can capture the exception with a block try...catch

var tokenObj;
try {
    tokenObj = JSON.parse(atob(base64));
}
catch(e) {
    logMyErrors(e);
}

The variable tokenObj I'm not sure that you have to declare it out, I guess it will depend on if you have "use strict"; but just in case it's not wrong there

You could also check if you have something stored in localstorage before trying to convert it as JSON

Update: The exception handling that Leandro says is fine but, in this case, it may be more convenient to control the error locally so that the execution flow continues. And better yet, avoid the error by checking the value before converting it.

    
answered by 18.02.2016 / 17:37
source
0

You could define a factory or provider that works with the $exceptionHandler

$ exceptionHandler in AngularJS

link

x.factory('$exceptionHandler', function () {
        return function (exception, cause) {
            alert(exception.message);
        };
    });

in this way if you throw a throw

x.controller('cont', function ($scope) {
        throw { message: 'error occurred' };
    });

the factory will control it globally

    
answered by 18.02.2016 в 17:31