gyozo kudor
gyozo kudor

Reputation: 6345

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.

Upvotes: 9

Views: 4349

Answers (2)

Jordy García
Jordy García

Reputation: 141

It depends in where you have placed the router-outlet. if you something like this:

<router-outlet></router-outlet>
<!-- Home Component Content -->

It will loads just like you say, with the other components content. To avoid this behavior you have to struct your main component like this:

<router-outlet></router-outle>

Just that and the things you want in all pages, including the error one.

Upvotes: -1

Zabavsky
Zabavsky

Reputation: 13640

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.

Upvotes: 7

Related Questions