Error handling is crucial in any application, and AngularJS provides $exceptionHandler
, a built-in service for global error tracking. This service allows developers to capture, log, and process unhandled exceptions across the application.
In this guide, we will cover:
- Understanding
$exceptionHandler
- Creating a Custom
$exceptionHandler
Service - Logging Errors to an External Server
- Using
$log
with$exceptionHandler
- Testing
$exceptionHandler
in Unit Tests - Best Practices for Error Handling in AngularJS
1. Understanding $exceptionHandler
The $exceptionHandler
service automatically captures unhandled errors occurring inside AngularJS applications. The default behavior is to log these errors to the browser console.
Example: Default Behavior
app.controller('MainController', function() {
throw new Error('Something went wrong!');
});
This will result in an error message being logged to the console:
Error: Something went wrong!
To customize error handling, we can override the $exceptionHandler
service.
2. Creating a Custom $exceptionHandler
Service
We can define a custom error handler to log errors, send reports to a server, or show user-friendly messages.
Custom $exceptionHandler
Implementation
app.factory('$exceptionHandler', function($log) {
return function(exception, cause) {
$log.error('Exception: ', exception);
if (cause) {
$log.error('Cause: ', cause);
}
// Custom logic: Send error to an external monitoring service
sendErrorReport(exception, cause);
};
});
// Function to send error data to a logging server
function sendErrorReport(exception, cause) {
console.log('Sending error report:', {
errorMessage: exception.message,
stackTrace: exception.stack,
cause: cause
});
}
How It Works
✔ Logs the error to the console using $log.error()
.
✔ Captures the cause (if available).
✔ Sends the error details to a server for further analysis.
3. Logging Errors to an External Server
In a real-world application, we might want to send errors to an external logging system like Sentry, Loggly, or a custom API.
Enhanced $exceptionHandler
with API Logging
app.factory('$exceptionHandler', function($log, $http) {
return function(exception, cause) {
$log.error('Error: ', exception.message);
if (cause) {
$log.error('Cause: ', cause);
}
// Send error details to a server
$http.post('/api/logErrors', {
message: exception.message,
stack: exception.stack,
cause: cause || 'Unknown'
});
};
});
Backend Example (Node.js/Express)
app.post('/api/logErrors', (req, res) => {
console.error('Error logged:', req.body);
res.sendStatus(200);
});
4. Using $log
with $exceptionHandler
AngularJS provides the $log
service for logging different severity levels (info
, warn
, error
, etc.). This helps in structuring logs for better debugging.
Example: Categorizing Errors
app.factory('$exceptionHandler', function($log) {
return function(exception, cause) {
if (exception.message.includes('Critical')) {
$log.error('Critical Error:', exception.message);
} else {
$log.warn('Non-Critical Error:', exception.message);
}
};
});
✔ $log.error()
→ Logs critical errors.
✔ $log.warn()
→ Logs minor issues.
5. Testing $exceptionHandler
in Unit Tests
To ensure $exceptionHandler
works correctly, we can write unit tests using Jasmine and Karma.
Unit Test for $exceptionHandler
describe('$exceptionHandler Test', function() {
var $exceptionHandler, $log;
beforeEach(module('myApp'));
beforeEach(inject(function(_$exceptionHandler_, _$log_) {
$exceptionHandler = _$exceptionHandler_;
$log = _$log_;
spyOn($log, 'error');
}));
it('should log an error message', function() {
var error = new Error('Test Error');
$exceptionHandler(error);
expect($log.error).toHaveBeenCalledWith('Exception: ', error);
});
it('should log the cause if provided', function() {
var error = new Error('Test Error');
var cause = 'Invalid Input';
$exceptionHandler(error, cause);
expect($log.error).toHaveBeenCalledWith('Cause: ', cause);
});
});
✔ Uses spies to track $log.error
calls.
✔ Verifies errors are logged correctly.
✔ Ensures the cause is logged if provided.
6. Best Practices for Error Handling in AngularJS
Always log errors in a structured format.
Send errors to a remote server for monitoring.
Use $log
to differentiate error levels (warn
, error
, info
).
Display user-friendly error messages instead of raw stack traces.
Test $exceptionHandler
to verify correct logging behavior.