Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect correctly in a global error handler

I have this global error handler:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler  
    {
        constructor(private injector: Injector) {
            super(false);
        }

        handleError(error) {
            super.handleError(error);
            const router = this.injector.get(Router);
                router.navigateByUrl('/error');
        }

    }

I put it in app.module:

  providers: [
    {
      provide: ErrorHandler, 
      useClass: GlobalErrorHandler
    }
  ]

to test this I throw an error inside a service. For some reason the error component shows up together with the other contents of the page. Something like this:

if I test the error component by going to /error it shows up like this (the error page is a paragraph with a single line):

Sorry, something went wrong!

but when I go to my home page where the error should trigger it shows up like this:

Sorry, something went wrong!

....
... Original content for /home
....

Sorry, something went wrong!

Can someone enlighten me what am I doing wrong?

Update

I've updated to angular-cli 1.5.2 AND also updated to angular 5 and the bug seems fixed there. I can navigate to the error page using the router.

like image 876
gyozo kudor Avatar asked Nov 14 '17 14:11

gyozo kudor


1 Answers

I've made some research and here is the reason why it behaves this way:

Since you're throwing an error in your service, the component which is using the service cannot be destroyed, thus the router is not able to release it. Thanks @TetraDev for pointing this out.

While someone might think it's an Angular bug I cannot confirm because I haven't found an open issue regarding it (feel free to update the answer if you have the link).

In order to resolve your problem I suggest not to use Router in this case and perform a browser redirect window.location.href = '/error'; instead.

like image 192
Zabavsky Avatar answered Nov 19 '22 18:11

Zabavsky