Angular HTTP Error Handling

In the previous articles, we’ve learned about the basics of the HTTP mechanism and how to fetch data using HTTP. But what if an error occurs during fetching data using HTTP. In this article, we’ll learn about how to handle those errors in Angular. Error Handling is one of the most important jobs to do while developing an application.

NOTE: Before coming to this tutorial, we strongly recommend learning Angular services and fetching data using HTTP that we had uploaded before to make the most of this article.

HTTP Error Handling in Angular

Let’s follow the steps and see how to handle errors in Angular:

Step 1: Import catchError From Rxjs/Operators in the Student Service File

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})

export class StudentService {

  url="/assets/data/student.json";

  constructor(private http:HttpClient) { }

  getStudents():Observable <any> {
    return this.http.get<any>(this.url).pipe(catchError(this.handleError))
  }

  handleError() {
    return throwError("Server Error") 
  }
}
  • The above code is very much similar to the previous article. In addition, we’re using pipe, and inside we’re using catchError method, and inside that, we’re using handleError method, which will return the error.
  • Now create a handleError method ( also import throwError) and return the error message.

Step 2: Move to the component.ts File and Subscribe to the Service

import { Component,OnInit } from '@angular/core';
import { StudentService } from './student.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  title = 'my-app';

  constructor(private studentservice:StudentService){ }

  ngOnInit():void{
    this.studentservice.getStudents().subscribe(data=>{
      console.log(data)
    },(error)=>{
      alert(error)
    })
  }
}
  • The above code is pretty similar to the previous article. In addition, apart from data, we’re also accepting errors this time.
  • We’re showing the error in the alert form.

Step 3: Use the Wrong Api Url and See the Result

We’ve used the wrong api_url, and as a result of subscribing, we’re getting an error alert message showing Server Error.

angular http error handling

Conclusion

We hope this article has cleared your concepts on HTTP error handling. Error handling is one of the most important concepts to make a clarified application.

Leave a Reply

Your email address will not be published. Required fields are marked *