Sev*_*rin 11 http-error typescript angular-http-interceptors angular
我有一个HttpInterceptor来捕获错误并在模态中显示它们.除了错误代码和消息之外,我还想显示响应的主体,它实际上包含更准确的错误描述(例如,在500内部服务器错误上).我怎样才能在角度上实现这一目标?(我使用的是4.3.6版本.)
我已经查看了相关的问题,但像HttpErrorResponse._body或类似的答案对我不起作用.此外,在控制台中检查错误响应时,HttpErrorResponse.error设置为null.
以下是我的拦截器目前的样子:
@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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
Max*_*kyi 15
酒店应提供身体error,因此:
return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
console.log(error.error); // body
...
});
Run Code Online (Sandbox Code Playgroud)
以下是来源的实施要点:
if (ok) {
...
} else {
// An unsuccessful request is delivered on the error channel.
observer.error(new HttpErrorResponse({
// The error in this case is the response body (error from the server).
error: body, <--------------------
headers,
status,
statusText,
url: url || undefined,
}));
}
Run Code Online (Sandbox Code Playgroud)
要了解有关拦截器背后的力学的更多信息,请阅读:
为了充分利用 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
}
}
Run Code Online (Sandbox Code Playgroud)
之后,只需将 APIErrorResponse 而不是 HttpErrorResponse 分配给您的错误对象,并如上所述访问您服务器的自定义错误:error.error