Handling Errors Globally in Angular 4

https://i.sstatic.net/ffKEs.png

Attached is my code implementing a global handler. I am trying to extract the 'dashboard' from the 500 Error on zone.js. How can I achieve this within the global Handler? Is there a method to obtain the desired output?

import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { LogService } from './logging-service.service';
import * as StackTrace from 'stacktrace-js';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private errors = new Array<any>();
  constructor(public injector: Injector, public zone: NgZone) {
  }
  public handleError(error: any) {
    console.log('I am a global handler', JSON.parse(error));
    const logService = this.injector.get(LogService);
    const location = this.injector.get(LocationStrategy);
    const message = error.message ? error.message : error.toString();
    const url = location instanceof PathLocationStrategy
      ? location.path() : '';
    const callbackFun = function (stackframes) {
      const stringifiedStack = stackframes.map(function (sf) {
        return sf.toString();
      }).join('\n');
      console.log(stringifiedStack);
    };


    const errback = function (err) {
      console.log(err);
      console.log(err.stack);
    };
    window.onerror = function (msg, file, line, col, error) {
      // this.zone.fromError.subscribe(this.onZoneError);
      StackTrace.fromError(message).then(callbackFun).catch(errback);
      StackTrace.get().then(callbackFun).catch(message);
    };
    const handleErrorData = {
      // Json data to send to server
    };
    logService.logError(handleErrorData);
    throw error;
  }
  public onZoneError(error) {
    console.log(error);
    console.error('Error', error instanceof Error ? error.message : error.toString());
  }

}

Answer №1

Create a custom HttpInterceptor for handling requests and responses in Angular 4.3.x.

In the interceptor, capture errors and extract the individual parts of the request URL.

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

Issue with Angular ngFor: displaying only one name instead of all names in the loop

In my component.ts file, I have retrieved this data from an API call: [ [ { "name": "name one", "desc": "something here", }, { "name": &quo ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

Nested arrays in an Angular interface

As a newcomer to Angular with a background in Java, I am accustomed to setting up classes as data structures for my information. However, after doing some research, I have learned that interfaces should be used instead. I am facing an issue understanding ...

Error encountered: SQLITE_BUSY - Unable to access the database due to it being locked. This

router.post("/update-quiz", upload.single("file"), async (req, res) => { const transaction = await sequelize.transaction(); try { const actions = { "Multiple Choice": async (questions, transacti ...

The elusive cookie in NodeJS remained just out of reach

After setting a cookie using the code below: router.get("/addCartToCookie", function(req, res) { let options = { maxAge: 1000 * 60 * 15, httpOnly: true, }; let cartData = { name: "test cookie", slug: slugify(&quo ...

Unable to assign the value of 'innerHTML' to a null property during an AJAX request

I have searched through numerous articles on this site, but I haven't been able to find the solution I'm looking for. Every time I click a cell in my custom div table, I receive the frustrating message "Cannot set property 'innerHTML' ...

Issue with retrieving JSON data in chart object: Error reading property 'length' of undefined in Angular/ng2-charts

     I have successfully retrieved JSON data in the following format:    [2193,3635,8417,0] The data is coming from localhost:8080. I aim to utilize this dataset for displaying a pie chart. Below is the code snippet from one.html: <div> ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Is there a way to convert a json array to a javascript array in AngularJs?

I am new to Angular and front-end development and facing a challenge that I can't seem to overcome. After reassigning one variable to another: $scope.testarray = $scope.todos; only the 'todos' data is being displayed when using Angular bind ...

Modify the specified pattern with regex only if it does not appear in a particular location in the content

Our tool development heavily relies on regex for various functionalities. One key aspect involves replacing placeholders with actual values dynamically using standard JavaScript's `RegExp`. All placeholder formats are similar to this: {{key}} In mo ...

Angular project facing issues during Maven build process

Hi there, I'm currently facing some challenges while trying to deploy my Angular and Spring Boot application. Whenever I run the command mvn clean compile spring-boot:run, I encounter a build failure from my Angular pom file. The error message I am r ...

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

I am creating accordion-style bootstrap tables using data generated from an ng-repeat loop, all without the use of ui.bootstrap or jquery

My attempt at creating a table with rows filled using ng-repeat is not working as expected. I want a collapsible panel (accordion) to appear on click of each row, but only a single row is rendering with my current code. Here is a link to my code: var ap ...

Eliminate the JSON object within jqGrid's posted data

The web page I'm working on features Filters with two buttons that load data for jqGrid when clicked. Clicking 'Filter' generates a postData json object and sends it to the server, which is working perfectly. However, I'm facing an is ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

The Angular menu items that have dropdowns attached are not showing up on the screen at all

I have been working on developing a complex Angular menu, and while I have made progress with the overall structure, I am stuck on a particular issue. The menu needs to display different options based on the user's role, such as "admin." However, desp ...

Running the JavaScript code on a webpage using Selenium WebDriver

I am currently in the process of creating an automated test for a website, and I am encountering some difficulty trying to execute a specific function within the site's code. Upon inspecting the developer tools, I have identified the function I need ...