Skip to content

Instantly share code, notes, and snippets.

@bharat-tiwari
Last active February 13, 2018 21:36
Show Gist options
  • Save bharat-tiwari/6d6a1e318f191f0e32497f27aac71fa0 to your computer and use it in GitHub Desktop.
Save bharat-tiwari/6d6a1e318f191f0e32497f27aac71fa0 to your computer and use it in GitHub Desktop.
App Level Error Handler in Angular
import { AppDataService, AppNotificationService } from '../services';
import { AppError } from '../entities';
import { Injectable, Injector, ErrorHandler } from '@angular/core';
@Injectable()
export class AppErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error) {
//As AppErrorHandler would be loaded before AppDataService, hence we cannot insantiate AppDataService in constructor
//so get AppDataService using injector
const dataService = this.injector.get(AppDataService);
const errorMessage = error.message || 'Unknown error thrown. Please see stack';
// post the error to the server logs
dataService.addToLog({ title: errorMessage, description: error.stack });
// when throwing errors anywhere in app in try/catch blocks, we cast the error as AppError.
// AppError is a type to store error details
if (error instanceof AppError){
if (error.notifyUser){ //if user needs to be informed
const appNotificationService = this.injector.get(AppNotificationService);
appNotificationService.set({ type: error.type, message: error.message });
}
}
throw appError;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment