Zafiera Davids
Zafiera Davids

Reputation: 221

error from service not being caught in component.ts

Once a user logs in, I retrieve their userAccount. In the case that it is not returned, I throw an error in the service. I then proceed to catch the error in a component.ts controller.

For some reason the component.ts does not catch the error being thrown. In console, I can see the errors, but for some reason my component.ts does not catch it in the try/catch block.

I've tested it multiple times to see where it failed and it seems that the error message doesn't reach the catch statement.

This is in my service:

/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}

this is in my component.ts

try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) { 
         this.showUnknownLoginFailureMessage  = true;
     }

What I expect is for the error to be handled in component.ts

Is it possible? Am I doing the error handling properly or am I missing something?

I need some guidance.

Thanks in advance!

Upvotes: 0

Views: 641

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73721

You can handle the exception by moving the try... catch statement inside of the setTimeout callback:

setTimeout(() => {
  try {
    this._service.customer(this.url, this.route);
  } catch (e) {
    this.showUnknownLoginFailureMessage  = true;
  }
}, 1000);

See this stackblitz for a demo.

Upvotes: 1

Ala Abid
Ala Abid

Reputation: 2326

A try/catch won't catch anything in a callback passed to subscribe (or then, or setTimeout or anything smiilar) which runs on a different "tick" or "microtask". You have to catch errors in the task where they occurred.

There is a solution in this answer https://stackoverflow.com/a/50494803/7179294

Upvotes: 3

Related Questions