我在Web上发现,ErrorHandler可以将所有错误捕获为客户端错误,也可以捕获HTTPErrorResponse错误. 但在我的情况下,我只能在GlobalErrorHandlerService中捕获客户端错误,而另一个httpErrorResponse则无法捕获. 我做错了什么?
My app-module:个
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MainInterceptorService, multi: true },
{ provide: ErrorHandler, useClass: GlobalErrorHandlerService },
],
bootstrap: [AppComponent]
})
export class AppModule { }
My GlobalErrorHandler:个
import {ErrorHandler, Injectable} from '@angular/core';
import {HttpErrorResponse} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandlerService implements ErrorHandler{
constructor() { }
handleError(error: any): void {
console.log("Handler work")
if (error instanceof HttpErrorResponse){
console.log("HttpErrorResponse")
} else {
console.log("Not httpErrorResponse")
}
}
}
My intercepter:个
import { Injectable } from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {catchError, Observable, throwError} from "rxjs";
import {error} from "@angular/compiler-cli/src/transformers/util";
@Injectable({
providedIn: 'root'
})
export class MainInterceptorService implements HttpInterceptor{
private httpError = {
status: 0,
message: ''
};
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// req=req.clone({headers:req.headers.set("Auth","Bearer"+token)})
return next.handle(req).pipe(
catchError(
(error:HttpErrorResponse|Error)=>{
// server-side error
if (error instanceof HttpErrorResponse){
console.log("intercepter work")
return throwError(()=>new Error("Server side error"+error));
} else {
return throwError(()=>new Error("Client side error"+error))
}
}
)
)
}
}
My UserService个
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {User} from "../entity/user";
@Injectable({
providedIn: 'root'
})
export class UserService {
errors:any[]|undefined
private response:Response|undefined
constructor(private http:HttpClient) { }
readonly URL_BASE="http://****"
readonly URL_REGISTRATE="http://****"
registrUser(user:User):any {
return this.http.post<any>(this.URL_BASE+"/account/register", user)
}
loginUser(userName:string,password:string):any{
return this.http.post<any>(this.URL_BASE+"/account/signin",{userName,password})
}
}
如果你解释一下ErrorHandler的逻辑,那么我会很高兴的.