javascript / intermediate
Snippet
Global Error Handling with ErrorHandler
By implementing the ErrorHandler class, you can create a centralized catch-all for any unhandled exceptions in your Angular application, ensuring errors are logged even if they aren't caught locally.
snippet.js
1
2
3
4
5
6
7
8
@Injectable()export class GlobalErrorHandler implements ErrorHandler {handleError(error: any): void {const message = error.message ? error.message : error.toString();console.error('Captured Global Error:', message);// Send to logging service here}}
angular
Breakdown
1
implements ErrorHandler
Ensures the class follows the required structure for Angular's error handling.
2
handleError(error: any)
The method Angular calls automatically whenever an unhandled exception occurs.