【发布时间】:2018-11-14 02:19:26
【问题描述】:
假设我向服务器发送了post 请求以创建用户。如果服务器响应错误,我想从ErrorHandler 获取我提交的主体(表单)(附加到该请求)。这样做的原因是,例如,当“创建用户”失败时,我想显示一个通知,其中包含从表单中获取的一些详细信息和一个按钮,用于将您重定向回相应的页面,并使用检索到的字段再次填充表格。
这就是我的ErrorHandler 的样子:
@Injectable()
export class ErrorsHandler implements ErrorHandler {
constructor(
private injector: Injector,
) { }
handleError(error: Error | HttpErrorResponse) {
const errorsService = this.injector.get(ErrorsService);
const router = this.injector.get(Router);
const zone = this.injector.get(NgZone);
if (error instanceof HttpErrorResponse) {
// Server error happened
if (!navigator.onLine) {
return console.log('No Internet Connection.');
}
else if (error.status === HttpStatus.UNAUTHORIZED) {
console.log('ErrorsHandler handled HttpStatus Unauthorized. Navigating back to \'/login\' page.');
zone.run(() => router.navigate(['/login']));
}
else {
// Http Error
//How do I get the form from here? I need it for user notification.
return console.log('%c SERVER ERROR ', 'background: #222; color: #ff6961 ; font-size: 15px; border: 2px solid #ff6961;', error);
}
} else {
// Client Error Happend
// Send the error to the server and then
// redirect the user to the page with all the info
errorsService
.log(error)
.subscribe(errorWithContextInfo => {
router.navigate(['/error'], { queryParams: errorWithContextInfo });
});
}
}
}
【问题讨论】:
标签: angular error-handling angular-errorhandler