9. 專題 - Angular中的異常處理


  • 可以通過throwError(xxxError)向上層拋出自定義或現有的異常類
  • 自定義異常
import { ErrorType } from '../error-handling/error-type.enum';

export class XxxError extends Error {
    errorType: ErrorType;
    details: string;

    constructor(errorType: ErrorType, details?: string) {
        super();
        this.name = XxxError.name;
        Object.setPrototypeOf(this, XxxError.prototype);
        this.errorType = errorType;
        this.details = details;
    }
}
  • 全局的異常處理
    • 避免拋到最上層的未處理的異常暴露信息給用戶,而且不友好
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { environment } from 'environments/environment';
import { LoggerService } from '../logging/logger.service';
import { XxxError } from '../models/xxx-error.model';
import { NotificationService } from '../notification/notification.service';
import { ErrorService } from './error.service';


@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private readonly injector: Injector) { }

  handleError(error: Error | HttpErrorResponse) {

    const errorService = this.injector.get(ErrorService);
    const logger = this.injector.get(LoggerService);
    const notifier = this.injector.get(NotificationService);

    let message;
    let stackTrace;
    if (error instanceof HttpErrorResponse) {
      message = errorService.getServerErrorMessage(error);
    } else if (error instanceof XxxError) {
      message = errorService.getXXXErrorMessage(error);
      notifier.show(message);
      message += ' ' + errorService.getXXXErrorMessageDetails(error);
    } else {
      message = errorService.getClientErrorMessage(error);
      if (!environment.production) {
        notifier.show(message);
      }
      stackTrace = errorService.getStack(error);
    }
    logger.error(message, stackTrace);
  }
}

  • 特殊/經驗
    • HttpClient等模塊可以通過catchError等進行異常處理和重新拋出。
    • Observable的subscribe塊中,如果使用error => {}進行了異常的捕獲和處理,那么在其中throwError或者return throwError都不能再被全局的ErrorHandler捕獲到。
    • 有時需要在異常處理中進行一些收尾工作,如取消loading效果等。但自己要判斷好這里的error應不應該catch住,應不應該再給外層處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM