×

iFour Logo

Error Handling with Angular

Kapil Panchal - June 24, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Error Handling with Angular

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.

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:

ai-Hiring-banner

Error when button is pressed

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

ai-Hiring-banner

 

Error Page

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

ai-Hiring-banner

 

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

 

ai-Hiring-banner

 

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.

 
Error Handling with Angular Table of Content 1. Introduction 2. Why Do We Deal with Errors? 3. HTTP Errors 4. Client-side HTTP errors 5. What is the best way to deal with such errors? 6. Default Error Handling 7. Error Handling on a Global Scale 8. HTTP Error Interceptor 8.1.Error Page 8.2.Loading page 8.3.Error Dialog 9. Conclusion 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. Default Error Handling 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 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: Error when button is pressed 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();   Error Page The rotating upload dialog will open and let the user know that interacting with the back end is currently taking some time:   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 - Enquire Today. See here 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:     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.  
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
8 Reasons why .NET should be used for ERP software development
8 Reasons why .NET should be used for ERP software development

The impact of an ERP software system with a global market value of $41.69 billion at the start of 2021 was remarkable, and these statistics explain why it has been crucial for global...

Important features of the Aviation software
Important features of the Aviation software

The Airline industry is rapidly expanding and strives to be more productive and efficient. Technology advancement has completely changed the corporate world, and the Airline industry...

Top 10 emerging technology trends for Aviation industry
Top 10 emerging technology trends for Aviation industry

The Aviation industry is experiencing a ground-breaking change with the waves of technological advancements. The transformations with eclectic ideas are creatingwonders in the airport...