在我的 Angular-14 项目中,我正在实现全局 http-error-interceptor。
我是这个代码:
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router, private toastr: ToastrService) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError(err => {
if (typeof err.error === 'string'){
this.toastr.error(err.error);
} else if (typeof err.message === 'string') {
this.toastr.error(err.message);
} else {
this.toastr.error(err.error.message);
}
const error = err.statusText || err.error.message;
if (err.status === 0){
this.toastr.error(err.statusText, err.status);
}
if (err){
switch (err.status) {
case 500:
this.router.navigateByUrl('/server-error');
break;
case 422:
this.toastr.error(err.statusText + ': ' + err.error.message, err.status);
break;
case 404:
this.router.navigateByUrl('/page-not-found');
break;
case 403:
this.router.navigateByUrl('/forbidden');
break;
case 401:
this.toastr.error(err.error.message, err.statusCode);
break;
case 400:
this.toastr.error(err.error.message, err.status);
break;
case 405:
this.toastr.error(err.error.message, err.status);
break;
case 409:
this.toastr.error(err.error.message, err.status);
break;
default:
this.toastr.error('Something went wrong. Contact Adminstrator');
break;
}
}
return throwError(() => err);
})
)
}
}
我使用toastr来显示错误。
我遇到的问题是,拦截器显示两条消息。第一个是真正的错误(无效凭证),然后第二个是我的 api 后端的 URL 和 400。
当我控制台错误时,我有这个:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 400,
"statusText": "OK",
"url": "https://localhost:44361/api/v1/login",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for https://localhost:44361/api/v1/login: 400 OK",
"error": {
"data": null,
"successful": false,
"message": "Invalid Credentials",
"statusCode": 400
}
}
这种事每次都会发生。它伴随着真正的错误以及另一个显示 API URL 和 400 的错误。
如何阻止它显示api后端的url?
https://localhost:44361/api/v1/login 的 HTTP 失败响应:400 OK
谢谢
好吧,当你可以编写代码时,你可以尝试创建一个
cons.ts
文件作为常量:
login_url = this.environment.redirectUrl + '/login'
您将从 envronment.ts 导入
redirectUrl
,并在 environment.ts
中您可以像这样配置 url:
redirectUrl: 'https://localhost:44361/api/v1'
这样错误就可以这样显示:
...
"url": "login_url",
...