Global Error Handling in Angular
Tags: webdev, angular, javascript, typescript
Published: 2024-02-13 07:54:11


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmyk9ukj1bncwffsytuj.jpg)

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
```ts
({} as any).doSomething()
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgrtbu9ycgtkqtrs3wi4.png)


### Handle it
```ts
try {
  ({} as any).doSomething();
} catch (error) {
  this.toastService.showError(error.message);
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqc2wxhwh25ao6ztpnxt.gif)


-   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.

```ts
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);
  }
}

```

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

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

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

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7lng9z3ik3ibldbw1n1.gif)


-  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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tq0thwcdczrg1agl0hbc.gif)

    
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.

```ts
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);
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/te0459nzait8dss0xcjf.gif)


- 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](https://community.abp.io/posts/global-error-handling-in-angular-gjcb2f1e)