import { ErrorHandler , Inject , Injectable } from "@angular/core" ; import { ErrorLogService } from "./ErrorLogService" ; export interface LoggingErrorHandlerOptions { rethrowError : boolean ; unwrapError : boolean ; } export var LOGGING_ERROR_HANDLER_OPTIONS = { rethrowError : false , unwrapError : false } ; @ Injectable ( ) export class LoggingErrorHandler implements ErrorHandler { private errorLogService : ErrorLogService ; private options : LoggingErrorHandlerOptions ; constructor ( errorLogService , @ Inject ( LOGGING_ERROR_HANDLER_OPTIONS ) options ) { this . errorLogService = errorLogService ; this . options = options ; } public handleError ( error ) { try { console . group ( "ErrorHandler" ) ; console . error ( error . message ) ; console . error ( error . stack ) ; console . groupEnd ( ) ; } catch ( handlingError ) { console . group ( "ErrorHandler" ) ; console . warn ( "Error when trying to output error." ) ; console . error ( handlingError ) ; console . groupEnd ( ) ; } try { this . options . unwrapError ? this . errorLogService . logError ( this . findOriginalError ( error ) ) : this . errorLogService . logError ( error ) ; } catch ( loggingError ) { console . group ( "ErrorHandler" ) ; console . warn ( "Error when trying to log error to" , this . errorLogService ) ; console . error ( loggingError ) ; console . groupEnd ( ) ; } if ( this . options . rethrowError ) { throw ( error ) ; } } private findOriginalError ( error ) { while ( error && error . originalError ) { error = error . originalError ; } return ( error ) ; } } export var LOGGING_ERROR_HANDLER_PROVIDERS = [ { provide : LOGGING_ERROR_HANDLER_OPTIONS , useValue : LOGGING_ERROR_HANDLER_OPTIONS } , { provide : ErrorHandler , useClass : LoggingErrorHandler } ] ;