我使用中间件作为后端,它处理每个异常并生成JSON响应,如下所示:
{"error":"System.Exception: 'You must be logged in to perform this action.'"}
在我的Angular应用程序中,我想在每次异常发生时显示一个通知,其中包含异常文本,但我不完全确定如何实现这一点。
我想知道是否应该使用HttpInterceptor
——我也不知道如何正确注册它们——它们应该在root.module.ts
中注册才能在应用程序范围内工作,对吧?
有人能推荐一个变通方法或提供代码示例吗?
一定要使用拦截器。
首先创建一个服务并将其转换为拦截器:
import { Observable } from 'rxjs/Observable';
import {
HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.catch(err => { /* Display your error here */})
.handle(req);
}
}
接下来,你需要在你的模块中提供它:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true },
]
http-intercepter.ts
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import {
HttpEvent,
HttpHeaders,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { AppService } from './../../core/services/citizen/app-services/app.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private appService: AppService) {
}
/**
*
* @param req - parameter to handle http request
* @param next - parameter for http handler
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
/**
* Handle newly created request with updated header (if given)
*/
return next.handle(req).do((event: HttpEvent<any>) => {
/**
* Sucessfull Http Response Time.
*/
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
}
}, (err: any) => {
/**
* redirect to the error_handler route according to error status or error_code
* or show a modal
*/
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 0:
console.log("Error type 0")
break;
case 400:
console.log("Error type 400")
break;
case 401:
console.log("Error type 401")
break;
default:
break;
}
}
});
}
}
在模块中.ts:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
]