Angular Error Handler - How to get the component context from error?

Viewed 287

I need to send all the component's attribute values to REST API when there's a typescript error. . It'll be really helpful for me if i get the component's context(this) using which i can get the values of all attributes in that component.

Is there anyway to achieve it? ngDebugContext.view has the context but it's not available in the PROD mode.

[EDIT]

For example, let's take the following component.

export class MyComponent implements OnInit{
   constructor(service:BaseService){}

   public first = 'first'; //.................... LINE 1
   public second = ['a','b'];//.................. LINE 2

   ngOnInit(){
        let a = null;
        console.log(a.name); //................... LINE 3
   }

}

So at LINE 3 there'll be a type error and the controls goes to the error handler service.

@Injectable()
export class ErrorHandlerService extends ErrorHandler {
...................
...................
     handleError(error: Error | HttpErrorResponse) {
        //i need to get the values from LINE 1 & LINE 2 here.. 
     }
}

As soon as the control reached the error handler, all details regarding MyComponent is lost which i want to retrieve.

1 Answers

In debug mode, maybe you could try something like this

handleError(error: Error | HttpErrorResponse) {
        if(!(error instanceof HttpErrorResponse))
        {
            let component : any = error.ngDebugContext.elView? error.ngDebugContext.elView.component : null; 
            if(component instanceof MyComponent)
            {
                console.log(`Error in MyComponent: first ${component.first} second ${component.second}`);
            }
        }
     }

If may not work, and if it works if may not work on prod mode

Related