Skip to content

Instantly share code, notes, and snippets.

@loicknuchel
Last active March 9, 2017 17:37
Show Gist options
  • Save loicknuchel/fcf54e1e8d0bcaf60a6d to your computer and use it in GitHub Desktop.
Save loicknuchel/fcf54e1e8d0bcaf60a6d to your computer and use it in GitHub Desktop.
Error handling in angular
angular.module('app', [])
.config(function($provide, debug){
// catch exceptions in angular
$provide.decorator('$exceptionHandler', ['$delegate', function($delegate){
return function(exception, cause){
$delegate(exception, cause);
var data = {
type: 'angular',
url: window.location.hash,
localtime: Date.now()
};
if(cause) { data.cause = cause; }
if(exception){
if(exception.message) { data.message = exception.message; }
if(exception.name) { data.name = exception.name; }
if(exception.stack) { data.stack = exception.stack; }
}
if(debug){
console.log('exception', data);
window.alert('Error: '+data.message);
} else {
mixpanel.track('exception', data);
}
};
}]);
// catch exceptions out of angular
window.onerror = function(message, url, line, col, error){
var stopPropagation = debug ? false : true;
var data = {
type: 'javascript',
url: window.location.hash,
localtime: Date.now()
};
if(message) { data.message = message; }
if(url) { data.fileName = url; }
if(line) { data.lineNumber = line; }
if(col) { data.columnNumber = col; }
if(error){
if(error.name) { data.name = error.name; }
if(error.stack) { data.stack = error.stack; }
}
if(debug){
console.log('exception', data);
window.alert('Error: '+data.message);
} else {
mixpanel.track('exception', data);
}
return stopPropagation;
};
});
@caiyichen
Copy link

it's very useful,thanks~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment