Retrieving the HTTP Error Response Body in Angular using HttpInterceptor

I am currently working on implementing an HttpInterceptor in Angular to catch errors and display them in a modal. In addition to error code and message, I want to include the body of the response for a more detailed description of the error (such as in the case of a 500 internal server error). How can I go about achieving this in my Angular project? (I am using version 4.3.6.)

Despite looking into similar questions, solutions like accessing HttpErrorResponse._body have not been successful for me. Furthermore, when examining the error response in the console, I noticed that HttpErrorResponse.error is null.

Below is a snippet of how my interceptor is currently structured:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  public constructor(private httpErrorService: HttpErrorService) { }

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {
    }, (error: HttpErrorResponse) => {
      console.log('HTTPERROR INTERCEPTOR');
      console.log(error);
      if (error.status >= 400) {
        this.httpErrorService.onError(error);
      }
    });
  }
}

Answer №1

If you're using Angular versions prior to 6, this answer is for you.

Make sure to access the body through the error property, like so:

return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
  console.log(error.error); // body
  ...
});

You can also refer to the code snippet below taken directly from the original source:

if (ok) {
  ...
} else {
  // If the request fails, the error will be sent via the error channel.
  observer.error(new HttpErrorResponse({
    // Here, the error corresponds to the response body (server-side error).
    error: body,   <--------------------
    headers,
    status,
    statusText,
    url: url || undefined,
  }));
}

To delve deeper into how interceptors work, check out this insightful article:

  • Insider’s guide into interceptors and HttpClient mechanics in Angular

Answer №2

In order to maximize the benefits of Typescript, my usual approach involves creating an interface that extends HttpErrorResponse:

interface CustomAPIErrorResponse extends HttpErrorResponse {
   error: {
      id?: string
      links?: { about: string }
      status: string
      code?: string
      title: string
      detail: string
      source?: {
         pointer?: string
         parameter?: string
      }
      meta?: any
      }
}

Once this interface is defined, you can simply assign CustomAPIErrorResponse instead of HttpErrorResponse to your error object and access your server's specific error details using error.error as shown above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble displaying data with Angular 6 JSON object pipe

Having an issue with displaying tasks from a MongoDB project schema in HTML. The tasks are stored in a nested array and I want to show the task name and description. Here's the code: <div class="card-body"> {{project.taskName | json}} </ ...

Neither the child nor the parent are showing the ng-content

I'm working on a project with a child-parent structure and I have the following components: <app-parent> parent component <ng-content select=["parent"]></ng-content> <app-child></app-child> </app-par ...

Does it make sense to start incorporating signals in Angular?

The upcoming release, as outlined in RFC3, will introduce signal-based components with change detection strategy solely based on signals. Given the current zone-based change detection strategy, is there any advantage to using signals instead of the tradi ...

How can ngFor be used to iterate through a nested object that contains a list requiring indexing?

I attempted to display it in the following manner <tr *ngFor="let item of mf.data; let i = index;" [attr.data-index]="i"> <td>{{item.grouporganizationunit.organizationunitlist[i].organizationunits.name}}</td> However, an error is being ...

Expanding and collapsing table rows in Angular 5 sequentially

I have been attempting to implement an angular table row expand/collapse feature, but I am having trouble getting it to work correctly. I tried using the following URLs for assistance, but they did not seem to solve the issue. Any guidance would be greatl ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Generating dynamic rowspan values for nested levels within a multi-level table using JavaScript and a JSON array

Trying to dynamically calculate the rowspan for each cell in a nested JSON array, which represents a multi-level table structure. Example of input data: [ { "name": "goal1", "children": [ { ...

Is there a specific event or callback in MSAL-Angular that can be triggered upon completion of the signup process

Incorporating MSAL-Angular into our application, we are curious if there is an event or callback that triggers once a user successfully signs up, similar to the "msal:loginSuccess" event. ...

What is the process for upgrading TypeScript to the newest version using npm?

My current TypeScript version on my machine is 1.0.3.0 and I am looking to upgrade it to the latest version, which is 2.0. Could someone please guide me on how to accomplish this using npm? ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Strategies for resolving the TypeScript error code TS7009?

I am currently new to Typescript programming and in the learning phase. I encountered a problem while coding and received an error in the backend console. Here is the code snippet that caused the error: function employee(id:number,name:string) { this.i ...

Identifying the absence of Observable with combineLatest detection

I am looking to update my code so that before loading the detail category, it checks if it has already been loaded in the statement. If not, then the detail will be loaded. Any assistance is appreciated! CategoryProvider Constructor: private _obServers = ...

Exploring the concept of destructuring function props using TypeScript

I'm having trouble running a Flatlist with typescript because it only allows an expression function with destructured props. I can't seem to figure out how to destructure with the necessary type (Suggestion). Does anyone have a solution for this? ...

Having difficulties with binding 'this' in Angular/Javascript?

Currently, I am attempting to integrate the pullToRefresh package into my Angular application. Here is the code snippet: const ptr = pullToRefresh.init({ mainElement: '.dashboard-container', onRefresh() { ...

Convert image file to a React TypeScript module for export

Imagine a scenario where you have a folder containing an image file and an index file serving as a public API. Is there a method to rename the image file before reexporting it? Here is the structure of the folder: └── assets/ ├── index.t ...

Displaying error messages in Angular2 reactive forms depending on the validation failure condition

In my implementation, I've utilized a separate generic component for displaying errors to avoid redundancy in the HTML code. This approach prevents the need to chain and hardcode conditions directly into the template. Consider a scenario where a fiel ...

Angular Router automatically redirects to the base route from specific routes, but the issue is resolved upon refreshing the page

Have you ever experienced Angular Router redirecting the user back to the base url for certain routes? You might think it's an issue with the app-routing.module.ts file, but it gets even more bizarre. Anomaly #1 This strange behavior only occurs wh ...

There are no versions available for Angular NPM that match [email protected]

Here is the contents of my .npmrc file: registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true After deleting node_modules and attempting to install the packages, I encountered the follo ...

Incorporate the {{ }} syntax to implement the Function

Can a function, such as toLocaleLowerCase(), be used inside {{ }}? If not, is there an alternative method for achieving this? <div *ngFor="let item of elements| keyvalue :originalOrder" class="row mt-3"> <label class=" ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...