角度句柄可处理500个服务器错误 [英] Angular handle for 500 server errors

查看:115
本文介绍了角度句柄可处理500个服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改我的http调用以处理(捕获)500个服务器错误.我尝试调用API,但在函数的"err"部分收到"500(内部服务器错误)".我希望能够捕获它,但不确定如何.是否有一种简单的方法来执行此操作?

How can I modify my http call to handle(catch) for 500 server errors. I try calling an API but receive a '500 (Internal server error' in the 'err' part of the function. I would like to be able to catch it if possible but am not sure how. Is there a simple way to do this?

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

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

I am not using any headers, map, errorhandler etc. This is just a basic call.

推荐答案

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

If you want to intercept errors when using HttpClient service to make backend calls and don't repeat yourself in every call you make, you need to use interceptor.

这是我们在应用程序中使用的,并且根据错误类型:500、400、404、403,我们重定向,显示付款方式或仅显示吐司消息:

This is what we use in our application and depending on the type of error: 500, 400, 404, 403, we redirect, show payment modal or just show toast message:

Http状态错误代码:

Http status error codes:

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提供程序中,在其中您可以引导应用程序:

You also need to add the interceptor into @NgModule providers where you bootstrap your app:

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

根据您的需要修改代码-启动时-我们只是将内容记录到控制台.一旦安装了该拦截器,它将处理所有通过HttpClient服务发送的后端请求.

Modify the code according to your needs - when started - we were just logging things to the console. Once you have this interceptor in place, it will handle all backend requests that go though HttpClient service.

这篇关于角度句柄可处理500个服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆