Skip to content

Instantly share code, notes, and snippets.

@melcor76
Last active September 25, 2020 14:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melcor76/1adb9210ccf0bd611410eec29c89ad4a to your computer and use it in GitHub Desktop.
Save melcor76/1adb9210ccf0bd611410eec29c89ad4a to your computer and use it in GitHub Desktop.
Error handling - global-error-handler.ts
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