Angular 9: Trouble encountered with utilizing custom error handler for error instances

I'm currently working on implementing a custom error handling system in Angular using the ErrorHandler class.

This is what my Globalerror service looks like:

export class CustomErrors extends Error {
  button?: any;
  errObject: any;
  constructor() {
    super('custom');
    Object.setPrototypeOf(this, CustomErrors.prototype);
  }
}
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  // constructor(private injector: Injector) {}
  constructor() {}

  handleError(error: any) {
   
    console.log('custom error', error instanceof CustomErrors);

   }
}

In the component I'm testing:

ngOnInit() {
    try {
        throw new Error('error on do the thing');
    }
    catch (err) {
        const errs = new CustomErrors();
         //console.log('in service', errs instanceof CustomErrors);
          errs.button = 'Back to the start';
          throw err;
    }
}

However, the console message in the handleError function

 console.log('custom error', error instanceof CustomErrors);
always returns false.

I'm puzzled as to why it's not returning true.

Answer №1

If you are encountering issues with TypeScript, there is a known workaround that involves adding a type to your custom errors. You can find more information about this on this GitHub page.

To implement this workaround, consider defining your custom errors as follows:

export class CustomErrors extends Error {
  button?: any;
  errObject: any;
  get type(): string {
     return "CustomError";
  }
  constructor() {
    super('custom');
    Object.setPrototypeOf(this, CustomErrors.prototype);
  }
}

In addition, you can create an interface like AppError to enforce the type member for all custom error classes:

export interface AppError {
    type: string;
}

By implementing this interface in your custom error classes, you can simplify error checking by replacing instanceof with a check for error.type.

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

Incorporating a division using the data() method

Currently, I am in the process of generating a list of flash SWFs. The data for this list is retrieved through an ajax call, which returns a JSON object. To populate the rows with data, I utilize my makeAppRow function. makeAppRow = function(myData) { ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

How can I transfer an image from the clipboard onto a fabric.js canvas?

I am currently working on developing a function that will allow users to paste an image from their clipboard onto a canvas as a new fabric.Image(). However, every search result I come across either discusses cloning existing objects within the canvas or pa ...

Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token. The interesting thing is that the API works perfectly fine when accessed through POSTMAN. However, ...

I encountered a typescript error while trying to export my Class component within a Higher Order Component (HOC)

I'm encountering a TypeScript error with my HomePage Class Component. Below is the code snippet: import * as React from "react"; import { Dispatch, AnyAction } from 'redux'; import { connect } from 'react-redux&apos ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Is it necessary to append the path with __dirname when utilizing Node's fs.readFile()?

Illustration: fs.readFile(path.join(__dirname, 'path/to/file'), callback); compared to fs.readFile('path/to/file', callback); Both methods appear to function properly, prompting me to inquire whether I can omit the __dirname prefix, ...

Displaying a highchart once a form has been submitted in a separate file

Can someone assist with this issue? I am trying to display a Highchart from file_2 in file_1 using PHP, jQuery, and AJAX. Below is the script I am working with: SCR_test02.php <?php require "function.inc.php"; //require "showscr.php"; include "c ...

What could be causing NPM to generate an HTTP Error 400 when trying to publish a package?

My current goal is to release an NPM package named 2680. At the moment, there is no existing package, user, or organization with this specific name. Upon inspection of my package.json, it appears that everything else is in order. Here are all the relevant ...

Observing a refraction phenomenon in both the background scenery and the three-dimensional models

My goal is to apply a refraction material to a sphere object. The challenge is to make the sphere transparent enough to see not only the scene background but also other 3D geometry within the scene. One possible solution is to configure the envMap paramete ...

Menu rollout problem when clicking or hovering

I'm facing challenges in making my menu content appear when a user clicks or hovers over the hamburger menu. My app is built using Angular, and I've written some inline JavaScript and CSS to achieve this, but the results are not as expected. Here ...

How do I search for a JSON object in JavaScript?

I have an array containing screen resolutions and I need to find the correct resolution range for the user's viewport (I have the width x height of the current window). Here is the sample JavaScript array with JSON objects: [ {width:100,height:200, ...

Is it necessary to use `top` or `parent` when utilizing local scripts in an iFrame?

Is it possible to eliminate the use of top or parent in iFrame localized scripts, as the title suggests? Upon examining the screenshot below, I encounter a "not defined" error unless I include top or parent as a prefix to my function call. test(); does n ...

Creating dynamic routes in express to enable flexible and customizable paths

Exploring the dynamic usage of paths in Express has been on my mind. Specifically, I have been employing lodash to locate a path in a separate file using regex methods. routes.js const json = require('./routes.json') const _ = require('l ...

I'm looking to provide the average rating of a restaurant along with the name of the owner

Currently, I am utilizing knex to craft queries for my express server. Within my database, I have two tables structured as follows: My objective is to establish a join between the two tables using the "owner_id" foreign key. Subsequently, I aim to retriev ...

Animated div or fieldset featuring a multi-step form

I have recently put together a detailed step-by-step guide. Each step is wrapped in its own "fieldset" within a single .html file. To navigate back and forth, I have incorporated javascript into the process. However, as time goes on, I am noticing that th ...

Transform js into a more dynamic format to avoid redundancy when displaying items upon click

I came across a simple lightbox code snippet, but it's based on IDs and I plan to use it for more than 20 items. I don't want to manually write out 20 JavaScript lines when there could be a more efficient way to handle it dynamically. My JS skill ...

Encountering an error while unit testing Angular components with MatDialog: "Error: <spyOn>: open has already been spied upon."

Once I create an HTML file with a button, I trigger a poll to appear after an onClick event. Then, when the "submit" button is clicked on the dialog window, it closes and I intend to execute subsequent methods. In my TypeScript file: openDialogWindow() { ...

Updating the dropdown option value in Angular 10's edit component

In my Angular and ASP.NET application, I have an edit form in a component with multiple select options in a dropdown list. When displaying all data in the edit form, the dropdown list fields are displayed as empty instead of showing the previously stored v ...

Tips for utilizing data attribute in jQuery programming

How can I modify my jQuery code to select the data attribute "data-price" instead of the value attribute? Sample HTML code: <span id="priceToSwap3"">$238</span> <select id="trapsize"> <option data-price="238">item1</option> ...