Home > database >  Angular interceptor handling [object,object]
Angular interceptor handling [object,object]

Time:11-02

Hi I'm trying to display nicely the errors for login/register etc through a toastr notification from my error interceptor.

The issue is sometimes I cant catch all the errors as I need.

Here is my 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((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);
      })
    );
  }
}

The issue is located here:

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();
          }

This type of error it works well. enter image description here

But here comes the issue when there are mulptiple errors enter image description here

or like that enter image description here

I tried many approches but noting is seems to work. Those any can take a look? How can i catch all those types of errors and display them correctly

CodePudding user response:

You probably need to do something like:

if(Array.isArray(error.error) {
   error.error.forEach( item => {
     modalStateErrors.push(item); // or whatever value you need from item
   })
}
else {
   modalStateErrors.push(error.error);
}
  • Related