Error Handling with Angular
Tags: angular, webdev, beginners, react
Published: 2023-06-30 08:41:32

## Introduction
In this blog, we will learn the most popular error handling solutions in Angular. Before making a move on to the subject let’s conceive why can we have errors in our apps? Why can't we write code from the always-on spec? To understand this simply, humans create software, and we're at risk of making mistakes. Some causes of errors can be:

- Complexity of application
- Communication between stakeholders
- Developer mistakes
- Time pressure
- Lack of testing, etc.

This list goes on and on. With this in mind, there comes a time when the unexpected happens, and a miscalculation is thrown.

## Why Do We Deal with Errors?
The most important aspect of application development is error handling. These flaws obstruct our efforts. Once something goes wrong, the application will throw an error. Angular handles problems, but it doesn't do anything other than writing them to the console. That's inconvenient for both the user and the developer. Surprising errors will happen any time, form of an association break, a null exception, no net access, Associate in Nursing unauthorized user, or a session invalid.

There are 2 kinds of error handling mechanism in Angular.

- HTTP Errors.
- Client-side Errors.

## HTTP Errors

When you use the client module HTTP to send an HTTP request, HTTP errors emerge. There are two types of errors here. One of these is a server-generated event, such as an unauthorized user, session expiration, or server downtime. When the client tries to retrieve the HTTP request, the opposite is created. These problems could be caused by a network fault, a request generation issue, or something else entirely.

## Client-side HTTP errors
Client-side HTTP errors relate to all errors that occur as a result of a code unit. It demonstrates that there is a flaw in the code.

## What is the best way to deal with such errors?

In Angular, there are two ways to handle these problems.

1. Default Error Handling
2. Global Error Handling

## Default Error Handling
We may simply utilize the try-catch mechanism to deal with the mistake in this technique. It's a tried-and-true method of dealing with mistakes.

**Syntax**
```
  handelerror()
  {
    try
    {
      // Your code here
    }  
    Catch(error)
    {
      // handle error here
    } 
  }

```

## Error Handling on a Global Scale
As delineated within the previous section, the GlobalErrorHandler category is registered as a provider within the ERP. once a fault happens at intervals the applying, this approach is known as. The error is provided as a parameter and should be out on a personal basis at intervals the technique. In our scenario, a dialogue looks at true where the error message has to be compelled to be displayed, and additionally the drawback is in addition recorded at intervals the browser console.

#### Read More: [A Complete Guide On Angular Rxjs Library](https://www.ifourtechnolab.com/blog/a-complete-guide-on-angular-rxjs-library)

The dialogue window is going to be closed in spite of whether or not the error is thrown outside of ngZone as a result of it's opened during an asking from zone.run. This is often the case, as an example, if a lifecycle binding error like the ngOnInit perform happens during a part.

**global-error-handler.ts**
```
  @Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private errorDialogService: ErrorDialogService, private zone: NgZone) {}
  handleError(error: Error) {
    this.zone.run(() =>
      this.errorDialogService.openDialog(
        error.message || "Undefined client error"
    ));
    console.error("Error from global error handler", error);
  }
}

```

In our example, there is a method in the AppComponent called localError which throws an error:

```
  localError() {
    throw Error("The app component has thrown an error!");
  }

```

So, if the primary button is pressed, this mechanism is named, and GlobalErrorHandler tackles the problem that was caused by displaying this dialogue:


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


The user will then click the Close button to dismiss the error dialogue and return to the application. Of fact, the mechanism of an error may differ from case to case, necessitating additional measures. For example, it is frequently useful to jot down the error message to a move log go in the back finish, to browse the application to a different page, or to reset a certain state when observing functions. In this case, we usually only show the error dialogue.

## HTTP Error Interceptor
Associate in Nursing hypertext transfer protocol fighter category completes the interception of hypertext transfer protocol mistakes. The method intercept is provided by the HttpErrorInterceptor class, which implements the interface HttpInterceptor. This method is applied mechanically to each hypertext transfer protocol request generated by our application, regardless of whether it is triple-crown or not. This also makes it possible for US to align a loading spinner. The first step is to invoke the service that will display the Loading Spinner dialogue:

this.loadingDialogService.openDialog();


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

Error Page
The rotating upload dialog will open and let the user know that interacting with the back end is currently taking some time:


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


Loading page
After that, the request protocol procedure is finished, which is essentially done with a handler protocol like the one below. The controller protocol provides a way for processing all requests and providing an RxJS response. As a result of this, the pipe methodology will be referred to, which gives the US the ability to use some RxJS operators to handle requests one by one.

#### Want to Hire Trusted [Angular Development Company](https://www.ifourtechnolab.com/angular-js-development-company) - Enquire Today.

We're going to be victimizing the catchError operator, which is dead whenever a mistake is thrown due to an improper request to the backend. The issue is only logged to the console within the application program as a primary action. The error window service is also known as "open the window with the error message" and "error response standing code" (for example, 404). Finally, we must deal with the error notification generated by the business throwError function, which takes the error as an input. Whether or whether the request delivers an error, the revolving loading dialogue is buried once more with the help of the slayer. — i.e. catchError was referred to as — or not.

In our sample application you can see that the following HTTP request does not need any additional error handling:

```
  failingRequest() {
    this.http.get("https://httpstat.us/404?sleep=2000").toPromise();
  }

```

The error dialog will look like this:


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

**Error Dialog**
Finally, it's value noting that the world error handler got conscious of the machine-readable text transfer protocol drawback moreover (you can see this at intervals in the browser console). However, no separate error dialogue window was generated during this state of affairs since the service for the error dialogue had already been activated by the machine-readable text transfer protocol error fighter antecedently, which prohibited a second dialogue from being opened at an equivalent time. commonly you may find some examples on the web, that use the instanceOf operator within the worldwide error handler to inform apart if it's an Associate in Nursing machine-readable text transfer protocol error or not. Throughout this case, the entire error handling — along with the machine-readable text transfer protocol errors — would be handled by the worldwide error handler. With this Angular version (v. 10) this can be unimaginable as a result of each error variety square measure merely recognized as “Error” by an instance of Associate in Nursingd there's no additional data regarding whether or not it's a hypertext transfer protocol error or not. thus this text shows an alternate approach to attain a similar error handling however with having it separated into the error handler, that catches everything Associate in Nursingd and fighter, that solely takes care of the hypertext transfer protocol errors.

## Conclusion
In this blog, we learn about the occurrence of errors, how do we deal with errors, different ways to handle the error. And there is some initial setup work involved, you will benefit in the long term from consistent error handling, which you will not have to worry about when new features are added to the program in the future. The loading spinner, which appears automatically for each request, is the same. Of course, these are only the essentials; specific changes and modifications to this method are feasible, depending on the needs of the application.