Angular 从HttpInterceptor中访问HTTP错误响应正文
我有一个HttpInterceptor来捕获错误并以模式显示它们。除了错误代码和消息之外,我还想展示响应的主体,它实际上包含了更精确的错误描述(例如,在500内部服务器错误上)。 我怎样才能做到这一点呢?(我使用的是4.3.6版。) 我已经看过了相关的问题,但像HttpErrorResponse之类的答案对我来说并不适用。 此外,在控制台中检查错误响应时,HttpErrorResponse.error设置为null 以下是我的拦截器当前的外观:Angular 从HttpInterceptor中访问HTTP错误响应正文,angular,typescript,http-error,angular-http-interceptors,Angular,Typescript,Http Error,Angular Http Interceptors,我有一个HttpInterceptor来捕获错误并以模式显示它们。除了错误代码和消息之外,我还想展示响应的主体,它实际上包含了更精确的错误描述(例如,在500内部服务器错误上)。 我怎样才能做到这一点呢?(我使用的是4.3.6版。) 我已经看过了相关的问题,但像HttpErrorResponse之类的答案对我来说并不适用。 此外,在控制台中检查错误响应时,HttpErrorResponse.error设置为null 以下是我的拦截器当前的外观: @Injectable() export clas
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
public constructor(private httpErrorService: HttpErrorService) { }
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
console.log('HTTPERROR INTERCEPTOR');
console.log(error);
if (error.status >= 400) {
this.httpErrorService.onError(error);
}
});
}
}
@Injectable()
导出类HttpErrorInterceptor实现HttpInterceptor{
公共构造函数(私有httpErrorService:httpErrorService){}
公共截获(req:HttpRequest,next:HttpHandler):可观察{
返回next.handle(req.do)(事件=>{
},(错误:HttpErrorResponse)=>{
log('HTTPERROR INTERCEPTOR');
console.log(错误);
如果(错误状态>=400){
这个.httpErrorService.onError(错误);
}
});
}
}
答案适用于低于6的版本。
正文应该在error
属性中可用,因此:
return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
console.log(error.error); // body
...
});
以下是实施的要点:
if(确定){
...
}否则{
//错误通道上传递了一个不成功的请求。
观察者错误(新的HttpErrorResponse({
//本例中的错误是响应主体(来自服务器的错误)。
错误:body,为了充分利用Typescript,我通常创建一个扩展HttpErrorResponse的接口:
interface APIErrorResponse extends HttpErrorResponse {
error: {
id?: string
links?: { about: string }
status: string
code?: string
title: string
detail: string
source?: {
pointer?: string
parameter?: string
}
meta?: any
}
}
之后,只需将APIErrorResponse而不是HttpErrorResponse分配给您的错误对象,并访问您的服务器的自定义错误,如上所述:error.error谢谢!它现在确实可以工作了。实际上我使用的是4.3.6版(在我的原始问题中也进行了更新)错误为空。但是现在在4.4.6版上一切正常。我正要捕获错误消息,我正在研究如何在API请求成功完成时提取成功消息,如状态代码200/201等。如何从return next.handle(req.do)(event=>{console.log)传递http响应(事件);//给出整个http响应})
我如何才能将此repsonse返回到我发出请求的组件。我使用的是ngrx 4这在Angular6中不再是这种情况,error.error返回一个Blob,而不是实际的正文字符串…@reven,感谢提供的信息,这意味着他们已经修复了它。@maxkoretskyiakawaizard那么当error.error返回时如何从HttpErrorResponse获取正文呢打一团?
interface APIErrorResponse extends HttpErrorResponse {
error: {
id?: string
links?: { about: string }
status: string
code?: string
title: string
detail: string
source?: {
pointer?: string
parameter?: string
}
meta?: any
}
}