【问题标题】:Angular handle for 500 server errors500个服务器错误的角度句柄
【发布时间】:2018-10-02 14:13:06
【问题描述】:

如何修改我的 http 调用来处理(捕获)500 个服务器错误。我尝试调用 API,但在函数的 'err' 部分收到 '500(内部服务器错误' ?

  call_http() {
    this.http.get<any>('/api/goes/here').subscribe(data => {
      this.result = data;
    },
      err => {
        console.log(err);
      });
  }

我没有使用任何标题、映射、错误处理程序等。这只是一个基本调用。

【问题讨论】:

标签: angular angular-httpclient


【解决方案1】:

如果您想在使用HttpClient服务进行后端调用时拦截错误,并且在每次调用中不重复自己,则需要使用拦截器。

这是我们在应用程序中使用的内容,具体取决于错误类型:500、400、404、403,我们重定向、显示支付模式或仅显示 toast 消息:

Http状态错误码:

export class HttpError{
    static BadRequest = 400;
    static Unauthorized = 401;
    static Forbidden = 403;
    static NotFound = 404;
    static TimeOut = 408;
    static Conflict = 409;
    static InternalServerError = 500;
}

拦截器代码:

import {Injectable, Injector} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'
import {Observable} from 'rxjs/Observable';
import {AuthorizationService} from "../authorization.service/authorization.service";
import {HttpError} from "./http-error";
import {Router} from "@angular/router";
import {Toaster} from "nw-style-guide/toasts";

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
// Regular dep. injection doesn't work in HttpInterceptor due to a framework issue (as of angular@5.2.9),
// use Injector directly (don't forget to add @Injectable() decorator to class).
constructor(private _injector: Injector) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const logFormat = 'background: maroon; color: white';

    return next.handle(req)
        .do(event => {
        }, exception => {
            if (exception instanceof HttpErrorResponse) {
                switch (exception.status) {

                    case HttpError.BadRequest:
                        console.error('%c Bad Request 400', logFormat);
                        break;

                    case HttpError.Unauthorized:
                        console.error('%c Unauthorized 401', logFormat);
                        window.location.href = '/login' + window.location.hash;
                        break;

                    case HttpError.NotFound:
                        //show error toast message
                        console.error('%c Not Found 404', logFormat);
                        const _toaster = this._injector.get(Toaster),
                            _router = this._injector.get(Router);
                        _toaster.show({
                            message: exception.error && exception.error.message ? exception.error.message :
                                exception.statusText,
                            typeId: 'error',
                            isDismissable: true
                        });
                        _router.navigate(['']);
                        break;

                    case HttpError.TimeOut:
                        // Handled in AnalyticsExceptionHandler
                        console.error('%c TimeOut 408', logFormat);
                        break;

                    case HttpError.Forbidden:
                        console.error('%c Forbidden 403', logFormat);
                        const _authService = this._injector.get(AuthorizationService);
                        _authService.showForbiddenModal();
                        break;

                    case HttpError.InternalServerError:
                        console.error('%c big bad 500', logFormat);
                        break;
                }
            }
        });
}

}

您还需要将拦截器添加到您引导应用程序的@NgModule 提供程序中:

    {
        provide: HTTP_INTERCEPTORS,
        useClass: ErrorInterceptor,
        multi: true
    },

根据您的需要修改代码 - 开始时 - 我们只是将内容记录到控制台。一旦你有了这个拦截器,它就会处理所有通过 HttpClient 服务的后端请求。

【讨论】:

  • 这应该是正确的答案。因为这是处理这些 4xx 和 5xx 错误的正确方法
  • 未处理的 5xx 错误的最佳答案!谢谢!
【解决方案2】:

您可以检查错误对象中的http状态码并警告用户或执行其他操作

call_http() {
    this.http.get<any>('/api/goes/here').subscribe(data => {
      this.result = data;
    },
      err => {
        console.log(err);
       // check error status code is 500, if so, do some action
      });
  }

【讨论】:

    【解决方案3】:
      err => {
        if(err.status==500)
        console.log(err)
      });
    

    }

    【讨论】:

      【解决方案4】:
      call_http() {
          this.http.get<any>('/api/goes/here').pipe(
            map(res => this.result = res),
            catchError(err => do something with err)
          ).subscribe();
      }
      

      以上内容应该允许您捕获错误并执行您需要的任何操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-30
        • 1970-01-01
        相关资源
        最近更新 更多