catchErrorWelcome back to CodeYourCraft! Today, we're going to dive into one of the essential aspects of Angular application development - Error Handling using the catchError function. 🎯
Error handling is crucial in any application to ensure a smooth user experience. In Angular, we use the catchError function to handle errors that occur during HTTP requests.
catchError? 💡The catchError function is a pipe that takes an error as input and returns an observable that emits an error message or a custom error object. It allows us to catch, handle, and manage errors in our Angular applications.
catchError 💡Let's create a simple service to demonstrate the use of catchError.
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://jsonplaceholder.typicode.com/todos/1')
.pipe(
catchError(this.handleError)
);
}
private handleError(err: HttpErrorResponse) {
let errorMessage = '';
if (err.error instanceof ErrorEvent) {
errorMessage = `An error occurred: ${err.error.message}`;
} else {
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage);
}
}In the above example, we've created a getData method that returns an HTTP GET request using Angular's HttpClient. The catchError function is used to catch any errors that might occur during the request.
The handleError method is where we handle the errors. It takes an HttpErrorResponse as an argument, which contains information about the error. We create an error message based on the error type and return it using throwError from RxJS, which creates an observable that emits the error message.
Now, let's use this service in a component to fetch data and display it.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `
<div *ngIf="data; else loading">
<h1>Data: {{ data }}</h1>
</div>
<ng-template #loading>Loading...</ng-template>
`
})
export class AppComponent implements OnInit {
data: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe(data => this.data = data);
}
}In the component, we've injected the DataService and subscribed to the getData method. If the request is successful, we assign the returned data to this.data. If an error occurs, the error message will be handled in the handleError method of the DataService.
What does the `catchError` function do in Angular?
That's it for today! Error handling is a crucial aspect of any application, and Angular provides us with powerful tools like catchError to handle errors effectively. In the next lesson, we'll dive deeper into error handling with more advanced examples. Until then, keep coding and happy learning! 💡🎯