zoukankan      html  css  js  c++  java
  • 9. 专题

    • 可以通过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住,应不应该再给外层处理。
  • 相关阅读:
    Linux内存地址映射
    江湖行
    数组/指针/const/字符串常量的使用传值问题
    TI davinci DM6467通过串口0将UBL和u-boot写入NAND flash
    CCS5配置使用GenCodecPkg生成CODEC SERVER
    typedef用法和与define的区别
    VS2008项目移植到Linux
    bootargs中ip段各项解释
    Davinci-DM6467板子-外围器件的I2C地址的疑惑解答
    MFC中界面自适应
  • 原文地址:https://www.cnblogs.com/wyp1988/p/13158547.html
Copyright © 2011-2022 走看看