Search code examples
javascriptangulartypescripterror-handlinginterceptor

How do I throw an error in a component and handle it in ErrorHandler?


There is my interceptor class, it should check if an error status is 401 and if it is it calls signOut() method from a service, if it isn't does nothing:

@Injectable()
export class MyErrorHandler implements ErrorHandler {
  constructor(
    private UserService: UserService,
  ) {
  }
  
  handleError(error) {
    if (error?.status === 401) {
      this.UserService.signOut();
    }
  }
}

There is my component:

@Component({
  ...
})
export class CartTableComponent implements OnInit {
  ...
  updateQuantity(i: number): void {
    this.CartService.update(i).subscribe(data => {
     ...
    })
  }
}

So it works. ErrorHandler handles it.

Then I need the component do something when it receives an error, so I add error state there:

@Component({
  ...
})
export class CartTableComponent implements OnInit {
  ...
  updateQuantity(i: number): void {
    this.CartService.update(i).subscribe(data => {
     ...
    }, error => {
       console.log('Some text should be shown when the method receives the error');
       throw new Error(error);
    })
  }
}

After I add error there ErrorHandler doesn't handle the error. The handleError() method receives [Object object] instead of object of error and it can't read error?.status.

How do I throw an error in a component and handle it in ErrorHandler?


Solution

  • Have you tried throwing the error directly? throw error instead of throw new Error(error);?

    Also, if you want to check requests, I think is better to use the HTTP_INTERCEPTOR with this approach your interceptor will be the first element to receive the error and can be handled (or passed) to the component accordingly.