Skip to content

Instantly share code, notes, and snippets.

@dagvany
Last active September 13, 2022 18:26
Show Gist options
  • Save dagvany/fb0c8a0f7274ac82e0f804462fd51ae3 to your computer and use it in GitHub Desktop.
Save dagvany/fb0c8a0f7274ac82e0f804462fd51ae3 to your computer and use it in GitHub Desktop.
Angular Error Handling POC
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ConsoleLogger } from './utils/consoleLogger';
.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ]
})
export class AppComponent implements OnInit, OnDestroy {
constructor(...) {
ConsoleLogger.overWriteConsoleLog();
}
ngOnInit(): void {...}
ngOnDestroy(): void {...}
}
import { NgModule, ErrorHandler, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorHandlerInterceptor } from './utils/httpErrorHandler.interceptor';
import { UiErrorHandler } from './utils/uiErrorHandler';
@NgModule({
declarations: [...],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorHandlerInterceptor,
multi: true
},
{
provide: ErrorHandler,
useClass: UiErrorHandler
},
ReadyService
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
var logPrefix = `[${new Date().toUTCString()}]`;
var log = console.log;
export abstract class ConsoleLogger {
public static setLogPrefix(prefix: string): void {
logPrefix = prefix;
}
public static overWriteConsoleLog(): void {
console.log = function(){
let args = Array.from(arguments);
args.unshift(`${logPrefix}: `);
log.apply(console, args);
}
}
}
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler, HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { catchError, Observable, of, tap } from 'rxjs';
@Injectable()
export class HttpErrorHandlerInterceptor implements HttpInterceptor {
intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(httpRequest)
.pipe(
catchError((errorResponse: HttpErrorResponse) => {
const errorMessage = errorResponse.error?.Message ?? errorResponse.message;
console.error(`${httpRequest.method} ${httpRequest.urlWithParams} ${errorMessage}`);
return of (errorResponse);
}),
tap((nextHttpEvent: HttpEvent<any>) => {
console.dir({
dateTime: new Date().toUTCString(),
method: httpRequest.method,
url: httpRequest.urlWithParams,
type: HttpEventType[nextHttpEvent.type],
body: nextHttpEvent instanceof HttpResponse ? nextHttpEvent.body : httpRequest.body
});
})
);
}
}
import { ErrorHandler, Injectable } from "@angular/core";
@Injectable()
export class UiErrorHandler implements ErrorHandler {
handleError(error: any) {
console.error("ehhh", error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment