嗨,我正在嘗試通過來自我的錯誤攔截器的 toastr 通知很好地顯示登錄/注冊等的錯誤。
問題是有時我無法根據需要捕獲所有錯誤。
這是我的攔截器
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((error) => {
if (error) {
switch (error.status) {
case 400:
debugger;
if (error.error.errors) {
const modalStateErrors = [];
for (const key in error.error.errors) {
if (error.error.errors[key]) {
modalStateErrors.push(error.error.errors[key]);
}
}
throw modalStateErrors.flat();
} else {
error.statusText = error.error;
this.toastr.error(error.statusText, error.status);
}
break;
case 401:
error.statusText = 'Unauthorized';
this.toastr.error(error.statusText, error.status);
break;
case 404:
this.router.navigateByUrl('/not-found');
break;
case 500:
const navigationExtras: NavigationExtras = {
state: { error: error.error },
};
this.router.navigateByUrl('/server-error', navigationExtras);
break;
default:
this.toastr.error('Something unexpected went wrong');
console.log(error);
break;
}
}
return throwError(error);
})
);
}
}
問題位于此處:
if (error.error.errors) {
const modalStateErrors = [];
for (const key in error.error.errors) {
if (error.error.errors[key]) {
modalStateErrors.push(error.error.errors[key]);
}
}
throw modalStateErrors.flat();
}
這種型別的錯誤效果很好。
![Angular 攔截器處理 [object,object]](https://img.uj5u.com/2021/11/02/90384922b361471fbec5b944c645358f.png)
但是當有多個錯誤時就會出現問題
![Angular 攔截器處理 [object,object]](https://img.uj5u.com/2021/11/02/8cf8e89d03134bbc948015bb8058917e.png)
或者像那樣
![Angular 攔截器處理 [object,object]](https://img.uj5u.com/2021/11/02/ee9da5bc418145f2b0402a5bdde238d6.png)
我嘗試了很多方法,但注意到似乎有效。那些可以看看嗎?我怎樣才能捕獲所有這些型別的錯誤并正確顯示它們
uj5u.com熱心網友回復:
您可能需要執行以下操作:
if(Array.isArray(error.error) {
error.error.forEach( item => {
modalStateErrors.push(item); // or whatever value you need from item
})
}
else {
modalStateErrors.push(error.error);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343777.html
