gpt4 book ai didi

angular - 如何从HttpErrorResponse获取请求的正文/内容? [Angular ErrorHandler]

转载 作者:行者123 更新时间:2023-12-03 08:10:28 30 4
gpt4 key购买 nike

假设我向服务器发送了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 });
});
}
}
}

最佳答案

我认为从HttpErrorResponse实例获取主体是不可能的,因为它扩展了HttpResponseBase,而后者没有正常的HttpResponse那样具有body属性。

 export declare class HttpErrorResponse extends HttpResponseBase implements Error {
readonly name: string;
readonly message: string;
readonly error: any | null;
/**
* Errors are never okay, even when the status code is in the 2xx success range.
*/
readonly ok: boolean;
constructor(init: {
error?: any;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
}

我所做的是使用响应感应器:
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ResponseBusiness } from '../Models/General/ResponseBusiness.model';
import { MsgService } from '../services/msg.service';
import { AlertService } from '../services/alert.service';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
constructor(private _msg: MsgService, private _alertService: AlertService) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

return next.handle(req).map(resp => {

const response = <HttpResponse<ResponseBusiness<Object>>> resp;

if (resp instanceof HttpResponse) {
}


/* do whatever you need with the req.body */

if (resp instanceof HttpErrorResponse) {
const body = JSON.parse(req.body);
if (body && body.avoidMsg) {
return resp;
}
}

if (response.status === 200 && !response.body.result.status) {
this._msg.setMsg({message: `${response.body.result.codeNumber} ${response.body.result.codeDescription}`, tipo: 'error'});
}
return resp;
});

}
}

然后像下面这样将inteceptor添加到app.module中:
providers: [
{provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true}],

关于angular - 如何从HttpErrorResponse获取请求的正文/内容? [Angular ErrorHandler],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292267/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com