遇到错误时获取完整的http响应

时间:2019-01-24 09:29:19

标签: angular error-handling rxjs

在角度文档中,他们说您必须在提供的选项上指定observe: "response"才能获得完整的http响应,我在这里做了

constructor(private service: new () => T,
  private http: HttpClient,
  private httpErrorHandler: HttpErrorHandlerService,
){ 
    this._handleError = this.httpErrorHandler.createHandleError(this.service.name);
}
private _handleError: HandleError;
//...other code
delete(resourceNameOrId: number | string): Observable<HttpErrorResponse>{
    return this.http.delete<T>(this._url + resourceNameOrId, {
      observe: "response"
    }).pipe(
      catchError(this._handleError(`delete`, null))
    );
  }

handleError函数在此服务中定义:

export type HandleError = <T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;

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

  constructor(private errorService: ErrorService, private modalService: NzModalService) { }

  createHandleError = (serviceName = '') => <T> (operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result);

  handleError<T> (serviceName = '', operation = 'operation', result = {} as T ){
    return (error: HttpErrorResponse): Observable<T> => {
      const message = (error.error instanceof ErrorEvent) ? error.error.message: `{error code: ${error.status}, body: "${error.message}"}`;
      this.errorService.errorMessage = `${serviceName} -> ${operation} failed.\n Message: ${message}`;
      console.error(this.errorService.errorMessage);
      return of(result);
    }
  }
}

这是我如何在组件中调用服务删除功能的示例:

this.service.delete(nom).subscribe(data => {
  if(!this.errorService.errorMessage){
    this.notificationService.success("Suppression", "L'enregistrement a été supprimée !");
  }
});

但是在我的情况下,指定observe: "response"无效,并且error: HttpErrorResponse仅返回错误消息,而不是完整的响应:

enter image description here

我在以下线程中尝试过解决方案:Angular 4.3.3 HttpClient : How get value from the header of a response?对我不起作用,提供的解决方案是定义观察选项。

我该如何解决?

更新:

observe选项仅在delete http请求返回200代码时才起作用,如下面的屏幕快照所示,但是当状态为404时,响应对象在此情况下为null,而在handleError函数中,响应主体为我唯一可以访问的东西。

enter image description here

2 个答案:

答案 0 :(得分:0)

如果要将HttpErrorResponse对象包含在catchError中,请尝试在api调用完成后将其放入块中,如下所示:

<div id="student-list" ng-controller="StudentController as ctlr"
     ng-init="ctrl.GetStudentDetails()" ng-cloak>

答案 1 :(得分:0)

通过拦截器拦截HttpClient挂钩是否合适? 试试这样的事情: 创建一个拦截器:

@Injectable()
export class FinalInterceptor implements HttpInterceptor {

constructor(private errorHandlerService: HttpErrorHandlerService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req).pipe(
        tap((event: HttpEvent<any>) => {
            if (event instanceof  HttpErrorResponse) {
              this.errorHandlerService.handleError(event);
            }
        }));
  }
}

AppModule:

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

所以在我的处理程序服务中,我遇到了HTTP错误 next console.log.

我想这正是您想要的