- 可以通过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住,应不应该再给外层处理。