error-handling - Angular GlobalErrorHandler 和 HttpErrorResponse - 解析器抛出格式错误的 HttpErrorResponse
问题描述
我在 Angular 6 应用程序中创建了全局错误处理程序:
主要错误处理方法:
handleError(error: Error | HttpErrorResponse) {
const router = this.injector.get(Router);
const notificationService = this.injector.get(NotificationsService);
this._logger(error);
if (!navigator.onLine) {
notificationService.displayNotification('error', 'timespan', {heading: 'Internet connection lost!', body: ''});
} else if (error instanceof HttpErrorResponse) {
notificationService.displayNotification('error', 'click', this._httpErrorMessage(error));
} else {
// CLIENT error
router.navigate(['/error-page']);
}
}
问题:许多 HTTP 服务调用是在解析器中执行的:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ClientDetailsModel> {
if (route.params.cif) {
const reqBody = new GetClientDetailsRequestModel({cif: route.params.cif, idWewPrac: this.userContext.getUserSKP()});
return this.clientsService.getClientDetails(reqBody)
.pipe(
map((clientDetails: { customerDetails: ClientDetailsModel }) => {
if (clientDetails.customerDetails) {
return clientDetails.customerDetails;
}
return null;
})
);
}
如果在这样的调用中发生 Http 错误,我的全局错误处理程序收到的错误将形成为包裹在 Error 中的 HttpErrorResponse(错误消息是 HttpErrorResponse):
Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":400,"statusText":"OK","url":"https://...
如果 Http 错误发生在解析器之外,则全局错误处理程序可以正常工作。
为了达到我的目标(从解析器抛出 HttpErrorResponse),我需要指定在订阅内的错误回调中处理错误的方式,但我不能这样做,因为解析器是管理订阅的人。
有没有办法指定解析器应该如何处理错误?
我想避免手动解析这些包装错误。
解决方案
我正在寻找解决方案,但只能创建一个工作循环。
这将检查 HttpErrorResponse 文本并尝试将 JSON 解析为真正的错误对象。
一点都不好,但总比没有好。
handleError(error: any): void {
console.error('Errorhandler catched error: ' + error.message, error);
// We need to have this little hack in oder to access the real error object
// The Angular resolver / promise wraps the error into the message, serialized as json.
// So we extract this error again.
// But first lets check if we actually dealing with an HttpErrorResponse ...
if (error.message.search('HttpErrorResponse: ')) {
// The error includes an HTTPErrorResponse, so we try to parse it's values ...
const regex = new RegExp('^.*HttpErrorResponse:\\s(\\{.*\\})$');
const matches = regex.exec(error.message);
if (matches !== null) {
// matches the regex, convert...
const httpErrorResponse = JSON.parse(matches[1]); // This is now the real error object with all the fields
this.handleHttpErrorResponse(httpErrorResponse);
} else {
// It contains HttpErrorResponse, but no JSON part...
this.toastr.error('There was an unknown communication error',
'Communication error',
{timeOut: 10000});
}
} else {
this.toastr.error('Unknown error occured',
'Well that should not happen. Check the log for more information...',
{timeOut: 10000});
}
}
推荐阅读
- swift - 何时在 swift 块中使用 [self] 与 [weak self]?
- c - 我制作了从一个文件复制数据并使用(读,写)粘贴到另一个文件的程序,但我认为它花费的时间太长
- python - 如何在 PyGame 中拖动多个图像?
- visual-studio - 无法在 Visual Studio 中为终端设置电力线字体
- tkinter - 从函数更改 tkinter bg
- lambda - 如何在 lambda 演算中减少 beta?
- tsql - TSQL:当 Scehma 更改时删除临时表会出错
- flutter - 里弗波德 | 真正需要多少个提供者才能只观察一个类的一个状态
- bash - 用于将一个大文件拆分为多个文件的 Unix 脚本,每个文件中有两对标签,每个文件都有一个文件名的命名约定
- python - 使用整数列表无法让 If-Statement 在 Jinja 中正确工作