在角度4中,使用拦截器的自定义错误处理程序,一切正常。以下是工作流程。
以下是我最了解如何处理错误的工作流程。
每当方法调用HTTP请求(使用HttpClient)并且响应都是错误而不是
appError
,这是个别错误类的实例,例如。 new AccessDenied(err.error))
AppError
类
super()
来使用父类方法。 并使用 error.interceptor.ts
中的throw Observable.error(appError)
发送此新创建的错误对象
现在,此错误由组件catch
中的HTTP请求的订阅者的app.component.ts
块处理
throw error
现在这个错误将由Global Error Handler( global-error-handler.ts )处理,它扩展了Angular的ErrorHandler
接口
AppError
的实例还是这是一个系统错误,然后在这里处理错误{ provide: ErrorHandler, useClass: GlobalErrorHandler }
this.authService.myMethod(`url`).subscribe({
(res) => { // successful response }
, (err) => {
if(err instanceof AppError) {
console.log('4. error display in html');
this.errorMessage = err.message;
} else {
throw err;
}
}
});
import { Router } from '@angular/router';
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpResponse, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthFail, BadInput, NotFoundError, ServerError, AccessDenied } from '../errors/';
import { AuthService } from './../auth/auth.service';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
private auth: AuthService;
constructor(private router: Router, private injector: Injector) { }
logout = false;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthService);
return next.handle(req).catch((err: HttpErrorResponse) => {
let appError;
console.log('1. error comes in interceptor: ', err);
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 401:
this.router.navigateByUrl('/login');
appError = new AuthFail(err.error);
break;
case 400:
appError = new BadInput(err.error);
break;
case 403:
appError = new AccessDenied(err.error);
break;
case 500:
appError = new ServerError(err.error);
break;
default:
appError = new Error(err.error);
}
return Observable.throw(appError);
}
});
}
}
import { AppError } from './app-error';
export class AccessDenied extends AppError {
constructor(error?: any) {
console.log('2. from interceptor', error);
const msg = error.message || " Access Denied";
super(msg);
}
}
import { Injectable } from '@angular/core';
export class AppError {
constructor(public message: string, public title: string = 'Error') {
console.log('3. parent class of custom error handler');
}
}
import { ErrorHandler, Injectable } from '@angular/core';
import { AppError } from './app-error';
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
constructor() {
super(true);
}
public handleError(error: any): void {
if (error instanceof AppError) {
console.log('5. App Error handled here in last', error);
// throw error;
);
} else {
console.error('An exception occured. Please try again.');
super.handleError(error);
}
}
}
现在我的查询是,如果我在if throw error
中写global-error-handler.ts
而不是在控制台中显示以下错误
未捕获(来自文件名Subscribe.js)
那么我们如何处理这个错误呢?我的意思是,如果我们从全局错误处理程序中编写throw error
而不是我们处理它的方式和位置?