IT이야기

각도 사용자 지정 오류 처리기가 약속에서 오류 유형을 가져오지 않음

cyworld 2022. 3. 14. 21:35
반응형

각도 사용자 지정 오류 처리기가 약속에서 오류 유형을 가져오지 않음

약속에서 해제된 경우 모든 오류 사용자 정의 오류 처리기가 실행 중인 경우 유형

import { HttpErrorResponse } from "@angular/common/http";
import { ErrorHandler, Injectable, Injector, NgZone } from "@angular/core";
import { MatSnackBar } from "@angular/material";

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

    constructor(private injector: Injector) { }

    handleError(error: any): void {
        if (error instanceof HttpErrorResponse) // this needs to be triggered
            this.injector.get(NgZone).run(() => this.injector.get(MatSnackBar).open(error.message))

        console.error(error)
    }

}

프로젝트 2가 존재하지 않기 때문에 findProject(2)는 HttpErrorResponse를 던진다.

일하는 중

this.projectService.findProject(2).subscribe()

작동하지 않음

await this.projectService.findProject(2).toPromise()

작동하지 않음

await this.projectService.findProject(2).toPromise().catch(error => { throw error })

작동하지 않음

try {
  await this.projectService.findProject(2).toPromise()
} catch (e) {
  console.log(e instanceof HttpErrorResponse) // true
  throw e
}

ProjectService는 관측 가능한 클래스를 반환하는 스위거 생성 클래스임

편집: handleError 메서드의 오류 개체:

Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"OK","url":"http://localhost:9090/api/project/2","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:9090/api/project/2: 404 OK","error":{"timestamp":1534921795114,"status":404,"error":"Not Found","exception":"de.dlh.lhind.lhindquiz.controller.ResourceNotFoundException","message":"No message available","path":"/api/project/2"}}
    at resolvePromise (zone.js:814)
    at zone.js:724
    at rejected (main.js:105)
    at ...

약속은 HttpErrorResponse를 규칙적인 Error and error.message를 감싸는 것처럼 보인다.

나는 단지 같은 이슈에 부딪혔을 뿐인데 너의 질문에 우연히 부딪쳤다.

필요한 경우 ErrorHandler에서 예외를 해제하여(적어도 각도 7에서) 해결할 수 있을 것 같다.

if (error.promise && error.rejection) {
    // Promise rejection wrapped by zone.js
    error = error.rejection;
}

// regular error handling code

참고: 나는 포장 에러 객체의 구조를 알아냈다.console.error("%O", error)이 질문에 따라:Chrome: 예외 세부 정보를 콘솔로 인쇄

참조URL: https://stackoverflow.com/questions/51951471/angular-custom-error-handler-not-getting-error-type-from-promise

반응형