skip to content
Alvin Lucillo

Check error status with HttpClient

/ 1 min read

💻 Tech

An HttpErrorResponse with status code of 0 may not indicate an API error but a client-side error. For example, invalid URL and parameters. Usually, API errors give status code like 404 and 403.

For example, in this standalone component, you can access the status code from the error object of type HttpErrorResponse

import { HttpBackend, HttpClient, HttpClientModule, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, HttpClientModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent implements OnInit {
  title = 'httpclient';

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get("https://api.restful-api.dev/object").subscribe({
      next: (data) => {console.log(data)},
      error: (error: HttpErrorResponse) => {
        console.error(error)
        console.log(error.status);
      }
    });
  }
}