我无法发现错误。
它正确地捕获了拦截器中的错误。
拦截器捕获错误
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 409,
"statusText": "Conflict",
"url": "myurl.com/url",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for myurl.com/url: 409 Conflict",
"error": {
"status": 409,
"message": "Email already exists"
}
}
但是在订阅中,错误将此值作为字符串:
Unknown error [object Object]
拦截器
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError(e => {
return throwError(() => e);
})
);
};
服务
@Injectable({
providedIn: 'root',
})
export class UserService {
private readonly _http = inject(HttpClient);
exists$(email: string): Observable<UserExistsResponse> {
return this._http.post<UserExistsResponse>(myurl.com/url, {
email,
});
}
}
组件
this._userService
.exists$(this.accountFormGroup.controls.email.value)
.subscribe({
next: res => {
// Do some stuff
},
error: e => {
console.log(e); // Prints : Unknown error [object Object]
this.setError(e);
},
});
app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(APP_ROUTES, withViewTransitions(), withPreloading(PreloadAllModules)),
provideHttpClient(
withXsrfConfiguration(environment.xsrf),
withInterceptors([authenticationInterceptor, errorInterceptor])
),
provideAnimationsAsync('animations'),
],
};
你试图在你的拦截器中返回 return throwError(() => e);,它实际上会返回一个 Observable 你可以阅读 ThrowError RxJs
的官方文档解决方案是直接抛出错误,而不使用 throwError for ex:
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError(e => {
throw e;
})
);
};