要实现在 Angular 中获取后端返回的 500 错误信息,并阻止前端页面弹出 500 错误提示框,可以使用 Angular 的 HttpInterceptor 拦截器来处理。

首先,创建一个错误处理拦截器:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler) {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 500) {
          // 阻止错误提示框弹出
          event.preventDefault();
          // 在控制台输出错误信息
          console.error('服务器错误:', error.error);
        }
        return throwError(error);
      })
    );
  }
}

然后,在 app.module.ts 中提供该拦截器:

import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';

@NgModule({
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ]
})
export class AppModule { }

现在,当后端返回 500 错误时,拦截器会阻止错误提示框弹出,并在控制台输出错误信息。你可以根据需求进一步处理错误信息,比如显示在页面上。

Angular 拦截 500 错误:获取信息并阻止提示框

原文地址: https://www.cveoy.top/t/topic/pKnE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录