-
-
Save melcor76/1adb9210ccf0bd611410eec29c89ad4a to your computer and use it in GitHub Desktop.
Error handling - global-error-handler.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ErrorHandler, Injectable, Injector } from '@angular/core'; | |
import { HttpErrorResponse } from '@angular/common/http'; | |
import { LoggingService } from './services/logging.service'; | |
import { ErrorService } from './services/error.service'; | |
import { NotificationService } from './services/notification.service'; | |
@Injectable() | |
export class GlobalErrorHandler implements ErrorHandler { | |
// Error handling is important and needs to be loaded first. | |
// Because of this we should manually inject the services with Injector. | |
constructor(private injector: Injector) { } | |
handleError(error: Error | HttpErrorResponse) { | |
const errorService = this.injector.get(ErrorService); | |
const logger = this.injector.get(LoggingService); | |
const notifier = this.injector.get(NotificationService); | |
let message; | |
let stackTrace; | |
if (error instanceof HttpErrorResponse) { | |
// Server Error | |
message = errorService.getServerMessage(error); | |
stackTrace = errorService.getServerStack(error); | |
notifier.showError(message); | |
} else { | |
// Client Error | |
message = errorService.getClientMessage(error); | |
stackTrace = errorService.getClientStack(error); | |
notifier.showError(message); | |
} | |
// Always log errors | |
logger.logError(message, stackTrace); | |
console.error(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment