ANG_FRONT

Capítulo 8.7. Componente de Error en Angular

Objetivo de la práctica

Duración aproximada

Instrucciones

  1. Generar el componente:

ng generate component error
  1. Definir la plantilla del componente:

<div class="error-container">
  <h1>¡Vaya! Ha ocurrido un error.</h1>
  <p>Lo sentimos, pero algo salió mal. Por favor, intenta de nuevo más tarde.</p>
  <a routerLink="/">Volver a la página principal</a>
</div>
  1. Estilo del componente:

.error-container {
  text-align: center;
  padding: 20px;
  color: #d9534f;
}
  1. Manejo de errores de navegación.

const routes: Routes = [
  // Rutas definidas
  { path: '**', component: ErrorComponent }
];
  1. Manejo de errores en servicios.

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('https://api.example.com/data')
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    // Aquí puedes realizar el manejo de errores
    console.error('Ocurrió un error:', error);
    return throwError('Algo salió mal; intenta de nuevo más tarde.');
  }
}
  1. Redirigir a componente de error en caso de error.

import { Router } from '@angular/router';

constructor(private router: Router) {}

someMethod() {
  this.dataService.getData().subscribe({
    next: data => {
      // Manejar los datos
    },
    error: err => {
      this.router.navigate(['/error']); // Redirigir al componente de error
    }
  });
}
  1. Interacción con el usuario.
  1. Registro de errores.