1

I have to create one service that will log any run-time error occurred in the application.

I have created a service named "ErrorHandlingService" and below given code is written

 import { ErrorHandler } from '@angular/core';
 export class ErrorhandlingService implements ErrorHandler {
     handleError(error: any): void {
         console.error('Some error occured: ', error);
     }
 }

In app.module.ts I have written the below code

 @NgModule({
     declarations: [AppComponent],
     entryComponents: [],
     providers: [StatusBar, SplashScreen,
         { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
         { provide: ErrorHandler, useClass: ErrorhandlingService },
     bootstrap: [AppComponent],
 })

But still the default error is shown

2
  • you seem to have missed setting it as a service @Injectable()
    – Suraj Rao
    Jul 17, 2019 at 8:40
  • I have got with the solution. I have just updated my code @Injectable({ providedIn: 'root' }) export class ErrorhandlingService implements ErrorHandler { Jul 17, 2019 at 9:28

2 Answers 2

0

How did you test that default error is being shown?

I tried with the same code you have written and it is working fine. Try testing by using,

throw new Error('error string')

Here's stackblitz -> https://stackblitz.com/edit/angular-yashpatelyk-random

Note : You don't need @Injectable() which is suggested in one comment since you are providing the class in the useClass.

0

I have updated by error handling code to below:

import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';

@Injectable({
     providedIn: 'root'
})
export class ErrorhandlingService implements ErrorHandler {
    handleError(error: any): void {
        const Dt = new Date().toISOString();
        if (error instanceof HttpErrorResponse) {
            console.log(Dt, '\r\nHTTP error: ', error.message, '\r\nStatus code:', (<HttpErrorResponse>error).status);
        }
        else if (error instanceof TypeError) {
            console.log(Dt, '\r\nType Error: ', error.message);
        }
        else if (error instanceof Error) {
            console.log(Dt, '\r\nGeneral Error: ', error.message);
        }
        else {
            console.log(Dt, '\r\nAnonymous Error: ', error);
        }
    }
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.