捕获Angular HttpClient中的错误


114

我有一个数据服务,看起来像这样:

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
        constructor(
        private httpClient: HttpClient) {
    }
    get(url, params): Promise<Object> {

        return this.sendRequest(this.baseUrl + url, 'get', null, params)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    post(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'post', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    patch(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'patch', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    sendRequest(url, type, body, params = null): Observable<any> {
        return this.httpClient[type](url, { params: params }, body)
    }
}

如果收到HTTP错误(即404),则会收到令人讨厌的控制台消息: 错误错误:未捕获(承诺中):来自core.es5.js的[object Object] 我该如何处理?

Answers:


230

您可以根据自己的需要选择一些选项。如果要根据每个请求处理错误,请在请求中添加一个catch。如果要添加全局解决方案,请使用HttpInterceptor

在此处打开正在工作的演示插件,以获取以下解决方案。

tl; dr

在最简单的情况下,您只需要添加.catch().subscribe(),例如:

import 'rxjs/add/operator/catch'; // don't forget this, or you'll get a runtime error
this.httpClient
      .get("data-url")
      .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more, see below
        console.error('An error occurred:', err.error);
      });

// or
this.httpClient
      .get("data-url")
      .subscribe(
        data => console.log('success', data),
        error => console.log('oops', error)
      );

但是,对此还有更多详细信息,请参见下文。


方法(本地)解决方案:记录错误并返回回退响应

如果只需要在一个地方处理错误,则可以使用catch并返回默认值(或空响应),而不是完全失败。您也不需要.map强制转换,可以使用泛型函数。来源:Angular.io-获取错误详细信息

因此,通用.get()方法将类似于:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class DataService {
    baseUrl = 'http://localhost';
    constructor(private httpClient: HttpClient) { }

    // notice the <T>, making the method generic
    get<T>(url, params): Observable<T> {
      return this.httpClient
          .get<T>(this.baseUrl + url, {params})
          .retry(3) // optionally add the retry
          .catch((err: HttpErrorResponse) => {

            if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', err.error.message);
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
            }

            // ...optionally return a default fallback value so app can continue (pick one)
            // which could be a default value
            // return Observable.of<any>({my: "default value..."});
            // or simply an empty observable
            return Observable.empty<T>();
          });
     }
}

处理错误将使您即使在URL处的服务状况不佳时也可以继续运行应用。

当您想为每个方法返回特定的默认响应时,这种按请求的解决方案非常有用。但是,如果您只关心错误显示(或具有全局默认响应),则更好的解决方案是使用拦截器,如下所述。

这里运行可运行的演示插件


高级用法:拦截所有请求或响应

Angular.io指南再次显示:

@angular/common/http拦截的主要功能是,它可以声明位于应用程序和后端之间的拦截器。当您的应用程序发出请求时,拦截器会先将其转换,然后再将其发送到服务器,并且拦截器可以在应用程序看到请求之前将响应转换回去。这对于从身份验证到日志记录的所有操作都是有用的。

当然,可以使用它以非常简单的方式来处理错误(此处为demo plunker):

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
         HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .catch((err: HttpErrorResponse) => {

        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
        }

        // ...optionally return a default fallback value so app can continue (pick one)
        // which could be a default value (which has to be a HttpResponse here)
        // return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));
        // or simply an empty observable
        return Observable.empty<HttpEvent<any>>();
      });
  }
}

提供拦截器:只需声明HttpErrorInterceptor以上内容,便不会导致您的应用使用它。您需要通过将其提供为拦截器,将其连接到您的应用模块中,如下所示:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './path/http-error.interceptor';

@NgModule({
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true,
  }],
  ...
})
export class AppModule {}

注意:如果您同时具有错误拦截器和某些本地错误处理,则很可能永远不会触发本地错误处理,因为错误将始终由拦截器处理之前到达本地错误处理处理。

这里运行可运行的演示插件


2
好吧,如果他想成为一个完全幻想的人,他将完全清楚他的服务:return this.httpClient.get<type>(...)。然后将catch...其实际用于服务的某个地方从服务中移出,因为那是他将建立可观察的流量并可以最好地处理它的地方。
dee zg

1
我同意,也许最佳的解决方案是让Promise<Object>的客户端(DataService的方法的调用者)来处理错误。范例:this.dataService.post('url', {...}).then(...).catch((e) => console.log('handle error here instead', e));。选择对您和您的服务用户更清晰的内容。
acdcjunior

1
无法编译:return Observable.of({my: "default value..."}); 给出错误“ | ...”,无法将其分配给'HttpEvent <any>'类型。
Yakov Fain

1
@YakovFain如果要在拦截器中使用默认值,则必须为HttpEvent,例如HttpResponse。因此,例如,您可以使用:return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));。我已经更新了答案以明确这一点。另外,我创建了一个工作演示的插件,以显示所有工作原理
acdcjunior

1
@acdcjunior,您是继续奉献的礼物:)
LastTribunal

67

让我请更新acdcjunior有关使用的回答HttpInterceptor与最新RxJs功能(第6节)。

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpErrorResponse,
  HttpHandler,
  HttpEvent,
  HttpResponse
} from '@angular/common/http';

import { Observable, EMPTY, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
        }

        // If you want to return a new response:
        //return of(new HttpResponse({body: [{name: "Default value..."}]}));

        // If you want to return the error on the upper level:
        //return throwError(error);

        // or just return nothing:
        return EMPTY;
      })
    );
  }
}

11
这需要得到更多的支持。迄今为止,acdcjunior的答案仍然无法使用
Paul Kruger

48

随着HTTPClientAPI 的到来,不仅Http替换了API,还添加了新的HttpInterceptorAPI。

AFAIK的目标之一是向所有HTTP传出请求和传入响应添加默认行为。

因此,假设您要添加默认的错误处理行为,请添加.catch()到所有可能的http.get / post / etc方法中。

可以通过以下方式使用a作为示例HttpInterceptor

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

/**
 * Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
 * and extract the relevant information of it.
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    /**
     * Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
     * @see HttpInterceptor
     * @param req the outgoing HTTP request
     * @param next a HTTP request handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch(errorResponse => {
                let errMsg: string;
                if (errorResponse instanceof HttpErrorResponse) {
                    const err = errorResponse.message || JSON.stringify(errorResponse.error);
                    errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
                } else {
                    errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
                }
                return _throw(errMsg);
            });
    }
}

/**
 * Provider POJO for the interceptor
 */
export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

// app.module.ts

import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';

@NgModule({
   ...
   providers: [
    ...
    ErrorInterceptorProvider,
    ....
   ],
   ...
})
export class AppModule {}

OP的一些额外信息:没有强类型的调用http.get / post / etc并不是对API的最佳使用。您的服务应如下所示:

// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
 // Define the form of the object in JSON format that your 
 // expect from the backend on post
}

export interface FooPatch {
 // Define the form of the object in JSON format that your 
 // expect from the backend on patch
}

export interface FooGet {
 // Define the form of the object in JSON format that your 
 // expect from the backend on get
}

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
    constructor(
        private http: HttpClient) {
    }

    get(url, params): Observable<FooGet> {

        return this.http.get<FooGet>(this.baseUrl + url, params);
    }

    post(url, body): Observable<FooPost> {
        return this.http.post<FooPost>(this.baseUrl + url, body);
    }

    patch(url, body): Observable<FooPatch> {
        return this.http.patch<FooPatch>(this.baseUrl + url, body);
    }
}

Promises从您的服务方法而不是返回Observables是另一个错误的决定。

还有一条建议:如果您使用的是TYPE脚本,则开始使用它的type部分。您失去了该语言的最大优点之一:知道要处理的值的类型。

在我看来,如果您想要一个很好的角度服务示例,请查看以下要点


评论不作进一步讨论;此对话已转移至聊天
deceze

我想这应该是this.http.get()等,而不是this.get()在等DataService
显示名称

所选答案现在看来更加完整。
克里斯·海恩斯

9

对于Angular 6+,.catch不能直接与Observable一起使用。你必须用

.pipe(catchError(this.errorHandler))

下面的代码:

import { IEmployee } from './interfaces/employee';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private url = '/assets/data/employee.json';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url)
                    .pipe(catchError(this.errorHandler));  // catch error
  }

  /** Error Handling method */

  errorHandler(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

有关更多详细信息,请参阅《 Http Angular指南》


1
这是唯一对我有用的答案。其他给出错误:“类型'Observable <未知>'不能分配给类型'Observable <HttpEvent <any >>”。
亚瑟王

8

非常简单(与以前的API相比)。

源自(复制和粘贴)Angular官方指南

 http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );

5

Angular 8 HttpClient错误处理服务示例

在此处输入图片说明

api.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Student } from '../model/student';
    import { Observable, throwError } from 'rxjs';
    import { retry, catchError } from 'rxjs/operators';

    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {

      // API path
      base_path = 'http://localhost:3000/students';

      constructor(private http: HttpClient) { }

      // Http Options
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }

      // Handle API errors
      handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(
            `Backend returned code ${error.status}, ` +
            `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError(
          'Something bad happened; please try again later.');
      };


      // Create a new item
      createItem(item): Observable<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

     ........
     ........

    }

2

您可能想要这样的东西:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

这在很大程度上还取决于您如何使用服务,但这是基本情况。


1

在@acdcjunior回答之后,这就是我的实现方式

服务:

  get(url, params): Promise<Object> {

            return this.sendRequest(this.baseUrl + url, 'get', null, params)
                .map((res) => {
                    return res as Object
                }).catch((e) => {
                    return Observable.of(e);
                })
                .toPromise();
        }

呼叫者:

this.dataService.get(baseUrl, params)
            .then((object) => {
                if(object['name'] === 'HttpErrorResponse') {
                            this.error = true;
                           //or any handle
                } else {
                    this.myObj = object as MyClass 
                }
           });

1

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

const PASSENGER_API = 'api/passengers';

getPassengers(): Observable<Passenger[]> {
  return this.http
    .get<Passenger[]>(PASSENGER_API)
    .pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}

0

如果您发现自己无法使用此处提供的任何解决方案捕获错误,则可能是服务器未处理CORS请求。

在这种情况下,Java语言(更不用说Angular了)可以访问错误信息。

在控制台中查找包含CORB或的警告Cross-Origin Read Blocking

此外,语法已更改以处理错误(如其他答案所述)。现在,您可以使用管道运算符,如下所示:

this.service.requestsMyInfo(payload).pipe(
    catcheError(err => {
        // handle the error here.
    })
);

0

通过使用拦截器,您可以捕获错误。下面是代码:

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Get Auth Token from Service which we want to pass thr service call
    const authToken: any = `Bearer ${sessionStorage.getItem('jwtToken')}`
    // Clone the service request and alter original headers with auth token.
    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json').set('Authorization', authToken)
    });

    const authReq = req.clone({ setHeaders: { 'Authorization': authToken, 'Content-Type': 'application/json'} });

    // Send cloned request with header to the next handler.
    return next.handle(authReq).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log("Service Response thr Interceptor");
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log("err.status", err);
        if (err.status === 401 || err.status === 403) {
          location.href = '/login';
          console.log("Unauthorized Request - In case of Auth Token Expired");
        }
      }
    });
  }
}

您可以首选此博客 ..给出一个简单的示例。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.