假设我向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 });
});
}
}
}