我收到500服务器错误(我期望)但我当前的实现没有捕获错误。应用程序在浏览器控制台中产生500服务器错误而不是捕获组件中的错误并处理错误,并且执行停止并且加载微调器仍然存在。我很难搞清楚这一点。我已经通过几种不同的方式重新构建了承诺而没有运气。
**更新**
我更新了服务以在promise中使用reject但仍然无效。
组件代码
save() {
this.loading = true; this.itemService.updateItems(this.updatedItems, this.activeCompanyId).then(() => {
this.loading = false;
}).catch((err) => {
console.log("Error updating items", err);
});
}
服务代码
updateItems(items:Item[], companyId) {
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);
return new Promise((resolve, reject) => {
this.http.post(`${this._config.API_URL}`, items, { headers }).subscribe(
data => {
resolve(data);
},
err => {
console.log('Error updating items', err);
reject(err);
}
);
});
}
如果出现错误,您要拒绝承诺:
updateItems(items:Item[], companyId) {
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);
return new Promise((resolve, reject) => {
this.http.post(`${this._config.API_URL}`, items, { headers }).subscribe(
data => {
resolve(data);
},
err => {
console.log('Error updating items', err);
reject(err);
}
);
});
}
我认为你的问题的解决方案可能是http拦截器:https://angular.io/api/common/http/HttpInterceptor
创建一个文件(例如error-interceptor.ts并在里面添加以下内容(确保将此类添加到模块的提供者)
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
catchError((errorResponse: HttpErrorResponse) => {
console.error(errorResponse.error);
})
);
}
}
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
顾名思义,您现在可以“拦截”所有传入的http响应并检查错误。根据您用于在背面发送回复的内容,您在错误后的回复(这是快递)。
res.status(500).json({ message: "Server Boo-Boo" });
然后您可以访问以下消息:
errorResponse.error.message;
我能够通过使用HttpIntercepter解决问题
import { Injectable } from "@angular/core";
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from "@angular/common/http";
import { Observable, of, throwError } from "rxjs";
import { catchError } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: AuthService, public navService: NavService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let request = req.clone({
withCredentials: true
});
return next.handle(request).pipe(catchError((err, caught) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 500) {
return throwError(err)
}
}
return of(err);
}) as any);
}
}