How to Handle Internal Server Error 500 in Angular 12

500 internal server error error handling is an important part of building an application in Angular. Error handlers provide an opportunity to information to the user and collect error information for development.

Let’s take a look at ways how can we handle an Internal Server Error 500  in Angular 12 Application?

In Angular, there are two categories Client-side and Server-side of errors that need to be handled differently. In this article, we will discuss both angular HTTP error handling using HttpInterceptor and HttpClient.

import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError } from 'rxjs/operators';
import { Router } from "@angular/router";


@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
    constructor(private _router: Router, private _snackBar: MatSnackBar) {

    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError(this.handleError)
        );
    }
    handleError(error: any) {

        // client-side error
        if (error.error instanceof ErrorEvent) {
            // display error message
            this._snackBar.open(error.message, "Error");
        }
        // server-side error
        else {
            if (error.status === 500) {
                //  redirect to error page 
                this._router.navigate(['/server-error']);
            } else {
                // display error message
                this._snackBar.open(error.message, "Error");
            }
        }
        return throwError(error.message);
    }
} 

in the above code, we have created a new method to handle error responses. when an error occurs, the user can easily see the message. for internal server error 500, we don’t want to show the user the exact error message that you get from the server. so we have redirected the user to a custom error page.

Handling the internal server error 500 in Angular Component

Here is an example component for fetching user details from the server. It looks like this.

Next, in the below code snippet,  the AppCompondnt fetches user details from the server. if something goes wrong during this request we need to handle exception this exception in some way.

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(private _router: Router,
    private _http: HttpClient,
    private _snackBar: MatSnackBar) {

  }
  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this._http.get<User[]>(environment.apiURL).subscribe(
      data => this.handleResponse,
      error => this.handleError
    )
  }

  // Successful responses.
  handleResponse(res: any) {

  }

  // Error responses
  handleError(error: any) {
    // client-side error
    if (error.error instanceof ErrorEvent) {
      // display error message
      this._snackBar.open(error.message, "Error");
    }
    // server-side error
    else {
      if (error.status === 500) {
        //  redirect to error page 
        this._router.navigate(['/server-error']);
      } else {
        // display error message
        this._snackBar.open(error.message, "Error");
      }
    }
  }
}
 

Above,  for internal server error 500, we are redirecting the user to an error page, and for other errors, an error notification will be displayed.

  • Post category:Angular
  • Reading time:3 mins read