I have this code for a token , generated with JWT
, then returned to the app if the user signed in successfully.
var token = $localStorage.token;
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
var tokenObj = JSON.parse(atob(base64));
then I 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 to get an error because it's not well built, but at this point I get an exception:
var tokenObj = JSON.parse(atob(base64));
I get in Angular a $exceptionHandler
in the debug console .
How can I control this error so that I don't get the exception from angular?
To avoid the error you can catch the exception with a block
try...catch
tokenObj
I'm not sure that you have to declare the variable outside, I guess it will depend on whether you have it"use strict";
but just in case it's not bad thereYou could also check if you have something stored in localstorage before trying to convert it as JSON
Update: The exception handling that Leandro comments is fine, but in this case it might be more convenient to handle the error locally so that the flow of execution continues. And better yet, avoid the error by checking the value before converting it.
You could define an
factory
orprovider
that works with the$exceptionHandler
$exceptionHandler in AngularJS
http://jsfiddle.net/stever/pypdm/
this way if you cast a
throw
the factory will control it globally