• 1000 консоли вместо обработки обработчика ошибок, то есть они даже не обращаются к обработчику ошибок.
ErrorHandler
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error: Error | HttpErrorResponse): void {
const errorService = this.injector.get(ErrorService);
const notifier = this.injector.get(NotificationService);
let message;
let stackTrace;
if(error instanceof HttpErrorResponse){
//Server error
message = errorService.getServerMessage(error);
stackTrace = errorService.getServerStack(error);
}else{
//Client Error
message = errorService.getClientMessage(error);
stackTrace = errorService.getClientStack(error);
}
notifier.showError(message);
}
}
Interceptor
export class ServerErrorInterceptorService implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// client-side error or network error
} else {
// TODO: Clean up following by introducing method
if (error.status === 498) {
// TODO: Destroy local session; redirect to /login
}
if (error.status === 401) {
// TODO: Permission denied; show toast
}
}
return throwError(error);
})
)
}
}
Module провайдер:
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
{ provide: HTTP_INTERCEPTORS, useClass: ServerErrorInterceptorService, multi: true}
]
и компонент:
export class ErrorHandlingComponent implements OnInit {
constructor(private httpClient: HttpClient) { }
numberArray: number[];
ngOnInit() {
}
causeError(){
this.numberArray[-1] = 1;
}
causeServerSideError() {
this.httpClient.get("STUB URL").subscribe((x: number[]) => this.numberArray = x)
}
}