【问题标题】:Print a string message within a error message in Angular在 Angular 的错误消息中打印字符串消息
【发布时间】:2019-12-13 21:20:24
【问题描述】:

如何从错误消息中打印字符串关键字。

我只想从错误消息中打印“错误请求”(在这种情况下)

"400 - Bad Request URL: put:http://x/y/z Message: Http 失败 http://x/y/z 的响应:400 错误请求详细信息:“错误请求””

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    我假设此错误消息来自您的后端(在 API 调用或其他情况下)。

    Angular 有一个叫做 HttpInterceptor 的东西,你可以实现它来处理各种事情,尤其是错误处理。

    基本HttpInterceptor示例:

    @Injectable()
    export class MyHttpInterceptor implements HttpInterceptor {
        private readonly _router: Router;
        constructor(_router: Router) {
            this._router = _router;
        }
    
        intercept( _request: HttpRequest<any>, _next: HttpHandler): Observable<HttpEvent<any>> {
            const req = _request.clone();
            return _next.handle(req).pipe(catchError( (_error: HttpErrorResponse, _caught: any) => {
                switch ( _error.status ) {
                    case 400:
                        console.error('Bad Request');
                        break;
                    case 401:
                        console.log('Unauthorized. Redirecting to Login');
                        break;
                    case 403:
                        console.error('Access Denied');
                        break;
                    case 404:
                        console.error('Resource not found');
                        break;
                    case 500:
                        console.error('Interval Server Error');
                        break;
                }
                return of(_error);
            })) as any;
        }
    }
    

    然后您可以将其连接到您的app.module.ts

    providers: [
       {
          provide: HTTP_INTERCEPTORS,
          useClass: MyHttpInterceptor,
          multi: true
        }
    ]
    

    HttpInterceptor 还有很多其他用例,例如将标头应用于每个请求(withCredentials 或类似的东西),但它通常用于捕获错误。

    如果您只想打印错误的消息,您可以这样做(假设它的类型为HttpErrorResponse)

    HttpErrorResponse.message

    这是课程:

    class HttpErrorResponse extends HttpResponseBase implements Error {
      constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; })
      name: 'HttpErrorResponse'
      message: string
      error: any | null
      ok: false
    
      // inherited from common/http/HttpResponseBase
      constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = 200, defaultStatusText: string = 'OK')
      headers: HttpHeaders
      status: number
      statusText: string
      url: string | null
      ok: boolean
      type: HttpEventType.Response | HttpEventType.ResponseHeader
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2018-04-17
      • 1970-01-01
      相关资源
      最近更新 更多