DEV Community

Sinan Öztürk
Sinan Öztürk

Posted on

Global Error Handling in Angular

Image description

Error handling is how we deal with errors that go wrong when we are running a program. There is no code that runs perfectly forever :) Things can go wrong and your application might crash. So, in order to run your program smoothly you must handle errors. It is just not for keeping your application in a running state. It is also useful to show messages about the error to the client. Like what went wrong, why it is not allowed to access this page etc.

How to handle errors

  • First of all, you have to catch them 😀. You can catch them via try-catch block. See an example; ### Create an basic error
({} as any).doSomething()
Enter fullscreen mode Exit fullscreen mode

Image description

Handle it

try {
  ({} as any).doSomething();
} catch (error) {
  this.toastService.showError(error.message);
}
Enter fullscreen mode Exit fullscreen mode

Image description

  • See, we catch the error and handle it.
  • In this case, we know where the error will be thrown. Most of the time we won't know where the error will appear. Should we cover the entire application with try-catch blocks? Of course not 😀
  • We are going to handle errors globally. Angular provides a great way to do it. Let's do it step by step;

1.Create a service and implement the ErrorHandler interface.

import { ErrorHandler, Injectable, inject } from '@angular/core';
import { ToastService } from './toast.service';

@Injectable({
  providedIn: 'root'
})
export class CustomErrorHandlerService implements ErrorHandler {
  toastService = inject(ToastService);

  //This method comes from interface
  handleError(error: any): void {
    this.toastService.showError(error.message);
  }
}

Enter fullscreen mode Exit fullscreen mode

2.Provide the service by using the ErrorHandler class from @angular/core.

import { ErrorHandler } from '@angular/core';

providers: [
  { provide: ErrorHandler, useExisting: CustomErrorHandlerService }
]

Enter fullscreen mode Exit fullscreen mode

Image description

  • It behaves exactly the same. Nice, now we catch the entire errors in one simple service.
  • Is it that simple? I wish it is but it's not 😀. This handling mechanism only works synchronously. When we start making http requests, our CustomErrorHandlerService won't catch the errors.

How to handle HTTP Requests

Make an HTTP request and check if it's working.

Image description

As you can see it doesn’t work. So how can we catch the http errors? with catchError() operator in rxjs or observer object. I will go with catchError() operator.

getTodo(id: number) {
  this.http
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .pipe(catchError((err) => {
     this.toastService.showError(err.message);
     return EMPTY;
        })
       )
      .subscribe(todo => this.todo = todo);
}

Enter fullscreen mode Exit fullscreen mode

Image description

  • So are we going to add this catchError() operator to the entire http requests? NO, we will use HTTP Interceptors!
  • Let's do it step by step.

For the rest of the article click here

Top comments (0)