Javascript 根据错误状态代码重定向到角度中的组件

Javascript 根据错误状态代码重定向到角度中的组件,javascript,angular,typescript,error-handling,Javascript,Angular,Typescript,Error Handling,我用四个部分来处理错误…一个用于服务器返回错误的http拦截器,一个基于内置角度错误处理程序的全局错误处理程序。一个错误服务,用于将错误记录到后端服务以供支持;一个材质对话框组件,用于向最终用户显示友好消息 有一些错误,我们希望捕获错误状态代码并重定向到组件以获得更友好的最终用户体验 一个例子是404。我们有一个未找到的组件。如果服务器错误状态为404,我希望重定向到未找到组件,并且不显示错误对话框 这是我的拦截器 import { Injectable } from '@angular/cor

我用四个部分来处理错误…一个用于服务器返回错误的http拦截器,一个基于内置角度错误处理程序的全局错误处理程序。一个错误服务,用于将错误记录到后端服务以供支持;一个材质对话框组件,用于向最终用户显示友好消息

有一些错误,我们希望捕获错误状态代码并重定向到组件以获得更友好的最终用户体验

一个例子是404。我们有一个未找到的组件。如果服务器错误状态为404,我希望重定向到未找到组件,并且不显示错误对话框

这是我的拦截器

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import * as StackTrace from 'stacktrace-js';
import { ErrorDialogComponent } from './error-dialog.component';
import { PathLocationStrategy } from '@angular/common';
import { ErrorService } from './error.service';
import { LoggerService } from './logger.service';
import { Router } from '@angular/router';

@Injectable()
/**
 * HttpErrorInterceptor to grab errors during http calls and log them
 *
 * @param (clientId) client id
 */
export class HttpErrorInterceptor implements HttpInterceptor {
  /**
   * constructor to grab errors during http calls and log them
   *
   * @param (dialog) MAT dialog to display to end user
   * @param (errorService) error service to grab error messages
   * @param (logger) logger service to post log errors to api and mantis
   */
  constructor(
    public dialog: MatDialog,
    private errorService: ErrorService,
    private logger: LoggerService,
    private router: Router
  ) {}
  /**
   * Interecept to grab request, deal with it and pass it along
   *
   * @param (request) http request
   * @param (next) send request to next http handler
   */
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // return the next statement
    return next.handle(request).pipe(
      // retry the call once
      retry(1),
      // catch the error
      catchError((error: HttpErrorResponse) => {
        if (error.status === 404) {
          console.log('error.status: ', error.status);
          // this.router.navigate(['']);
        } else {
          // Message variable to hold error message
          let errorMessage = '';
          // Variable to hold url location of error
          const url =
            location instanceof PathLocationStrategy ? location.path() : '';
          // server-side error
          errorMessage = this.errorService.getServerMessage(error);
          // get the stack trace, lets grab the last 10 stacks only
          StackTrace.fromError(error).then(stackframes => {
            const stackString = stackframes
              .splice(0, 20)
              .map(function(sf) {
                return sf.toString();
              })
              .join();
            /**
             * Function to log errors to api and mantis
             *
             * @param (errorMessage) error message passed to function
             * @param (url) url passed to function
             * @param (stackString) stackString passed to function
             */
            this.logger
              .createErrorLog(errorMessage, url, stackString)
              .subscribe(
                result => {
                  console.log('log filed: ', result);
                },
                (err: any) => console.log(err)
              );
          });
          // Check if error is undefined and open dialog with appropriate error info
          if (typeof errorMessage !== 'undefined') {
            this.openDialog(errorMessage);
          } else {
            this.openDialog('undefined');
          }
          // throw error
          return throwError(errorMessage);
        }
      })
    );
  }
  /**
   * Function to open dialog to display error
   *
   * @param (data) error data to display
   */
  openDialog(data): void {
    // Constant to hold and call dialog to display error
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });
    // Code to run after the dialog is closed
    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
    });
  }
}

那么,有没有办法捕获404代码并执行重定向,但不调用全局错误处理程序?

在Z.Bagley和他共享的链接的帮助下,我能够修复它。我注意到我错过了下一个.handle()调用

这是我修改过的拦截代码

if (error.status === 404) { 
    const newRequest = request.clone();
    return next.handle(newRequest); 
} 

创建Http错误拦截器。这将捕获在全局搜索之前返回的错误。使用
返回next.handle(req).pipe(catchError…
,找到404并强制路由器导航。然后,您可以
返回EMPTY
忽略404,或者
返回throwError(error)
将错误发送到全局处理程序。请参阅:有关拦截和处理http错误的示例。感谢您的反馈。我已经在使用http拦截器(参见上面的代码)。也许我的代码逻辑有错误?请告知。我查看了你的超链接,发现我错过了下一个.handle()调用。这很有帮助…谢谢!这是我修改过的拦截代码…````if(error.status==404){console.log('error.status:',error.status);const newRequest=request.clone();return next.handle(newRequest);}```
if (error.status === 404) { 
    const newRequest = request.clone();
    return next.handle(newRequest); 
}