代码之家  ›  专栏  ›  技术社区  ›  Renaud is Not Bill Gates

在发生错误时获取完整的http响应

  •  1
  • Renaud is Not Bill Gates  · 技术社区  · 7 年前

    在角度文档中,他们指出您必须指定 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))
        );
      }
    

    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 !");
      }
    });
    

    注意:“回应” 在我的情况下不起作用,而且 error: HttpErrorResponse

    enter image description here

    我已经尝试过这方面的解决方案: Angular 4.3.3 HttpClient : How get value from the header of a response? 这对我不起作用,提供的解决方案是定义observe选项。

    我怎样才能解决这个问题?

    “观察”选项仅在删除http请求返回200代码时有效,如下面的屏幕截图所示,但当存在404响应状态时,本例中的响应对象为null,在handleError函数中,响应主体是我唯一可以访问的对象。

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  0
  •   mihan oktavian    7 年前

    通过拦截器拦截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);
                }
            }));
      }
    }
    

    应用模块:

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

    所以在我的http错误处理程序服务中 next console.log.

    我想这正是你想要的

        2
  •  0
  •   Code_maniac    7 年前

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

    delete(resourceNameOrId: number | string): Observable<HttpErrorResponse>{
        return this.http.delete<T>(this._url + resourceNameOrId)
     .pipe(
          catchError((error:any)=>{
               console.log(error);//error is the HttpErrorResponse object returned
               return this._handleError(`delete`, null)
          })
        );
      }