Is it possible to modify the Angular global error handler to accept additional parameters besides just the error object?

After exploring the capabilities of https://angular.io/api/core/ErrorHandler, I have found that it allows me to override the global error handler with an error object. I appreciate how I can easily define my own global error handler and use it wherever necessary.

However, when working with RxJS, I find myself using

catchError(this.handleError(my, params, go, here))
frequently.

I wish to make my handleError() method global and integrate it into my global error handler. Unfortunately, it seems that this may not be technically feasible.

My handleError method is designed to log errors to a logger, console, and return a dummy Observable for smooth execution in combination with RxJS's catchError.

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private messageService: MessageService) { }

  public handleError<T>(
    error: HttpErrorResponse, operation = 'operation', result?: T) {
    var errorMessage = '';
    if (error.error instanceof ProgressEvent) {
      errorMessage = `Client error occurred: ${error.message}`;
    } else {
      errorMessage = `Adam's error ${error.status}: ${error.message}`;
    }
    console.error(errorMessage);
    this.messageService.add(`${operation} failed: ${errorMessage}`);
    return of(result as T);
  }

}

Is there a way to implement this as a global error handler? Or would it be better to approach it differently? While creating an "error service" to manage my generic handleError() and injecting it everywhere is a possibility, it does seem cumbersome.

Answer №1

If you find yourself needing to remove your classes from the Angular context, one potential option is to develop a custom operator for RxJS. While not a direct solution to the problem at hand, this workaround can be utilized as a last resort when no other solutions are available:

export function handleCustomError<T>(...args) {
  // It's important to avoid dependencies in the constructor outside of Angular's context
  const errorHandler = new GlobalErrorHandler();
  return catchError<T>(errorHandler.handleError(...args));
}

Answer №2

Initially, the handleError function does not return any value. It would be better to utilize the method of() to return an Observable.

Additionally, it's important to note that the GlobalErrorHandler's handleError function will handle all types of errors in your application, not just HttpErrorResponse instances. Considering this, returning an Observable for unexpected errors like division by zero seems unnecessary.

In my opinion, a more appropriate approach would be to use an http-interceptor if you want to catch and log errors specifically from your API Server without disrupting the app's flow. By implementing an interceptor, you can intercept errors, perform necessary actions such as logging, and then continue with a custom response within the chain.

Learn about the Http interceptor interface

Explore logging with http interceptors

Read more on intercepting http requests

Feel free to share how you implement this solution. I am here to provide further assistance if needed.

Best regards, Max.

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

ngx-bootstrap - Not Triggering On Hide Event

Having trouble triggering a function in my Angular component when closing a modal from ngx-bootstrap. No matter what method I use, I can't seem to catch the event. The event I want to trigger is simple - just need to see it in the console for now: // ...

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

Angular Floating Panels: A Guide to Creating Dynamic User Interfaces

In the process of developing an angular app, I require a dock-able panel. After researching available controls online, I found them difficult to use and they compromised our screen layout. As a result, I am considering building a custom dock panel from s ...

What is the proper way to integrate plotly types in Angular using a local version?

After exploring various plotly packages, I discovered that the angular-plotly package is no longer being updated. To incorporate the plotly library into my project, I decided to download the plotly.min.js file and include it in my sources. Additionally, I ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Is it possible in Typescript to reference type variables within another type variable?

Currently, I am working with two generic types - Client<T> and MockClient<T>. Now, I want to introduce a third generic type called Mocked<C extends Client>. This new type should be a specialized version of MockClient that corresponds to a ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

The dynamic change in the maximum value of the Ngb rating is not being accurately displayed in the length of the

The dynamic change in the maximum value of ngb rating is not being reflected in the length of the stars. Although two-way binding occurs with [max]="", the length of the stars remains unchanged. <ngb-rating [(rate)]="currentRate" [ma ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Angular routing functions flawlessly on Chrome Mac but encounters issues on Chrome iOS

Encountering a strange issue. My routing is properly configured and has been verified multiple times. Oddly enough, page1, page3, and page5 are functioning correctly, while page2, page4, and page6 fail to redirect as expected. Upon clicking the redirect ...

Encountering issues with compiling files in react app using webpack, failing to compile as anticipated

When it comes to compiling, I prefer using webpack with TypeScript files. In my webpack.config.js file: module.exports = async (env, options) => { const dev = options.mode === "development"; const config = { //Webpack configuration pr ...

Tips for sorting through aggregated information in Foundry Functions

How can I filter on grouped data in Foundry Functions after grouping and aggregating my data? See the code snippet below for reference: @Function() public async grouping(lowerBound : Integer ): Promise<TwoDimensionalAggregation<string>> { ...

Best practices for receiving messages from SQS in Node.js

I am exploring how to implement SQS in a similar manner as RabbitMQ or Kafka, where we usually set up a listener. However, after going through their documentation, I couldn't find any instructions on how to set up a listener for SQS: Currently, I am ...

Anglar2-useful-swiper does not automatically advance slides

I've been working on integrating the angular2-useful-swiper plugin into a single page application for image display, complete with auto rotation. However, I'm encountering an issue where the images are not transitioning as they should, and instea ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Enhance the express Response type and then export my updated type as a distinct module

I am currently working on developing a new 'common' module for my team. One of the key features it should have is an extension of both the response and request objects in Express. Our main goal is to achieve two things - first, extending the Req ...

What could be the reason why the keypress event doesn't seem to be functioning properly on

Currently, I am utilizing Angular and the Ionic framework. Here is a snippet of the HTML code that I have written: <div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCh ...

Switching positions in Azure DevOps (Angular + API): How can the Angular configuration be modified for the designated slot?

Setting up the Angular app can be quite tricky. In our Azure Yaml pipeline publishing job, we tackle the challenge by executing a "token" replacement to tailor the configuration for the specific target environment within a tokenized artifact. Subsequently ...