所以我使用httpClient.get()进行REST调用。我已经设置了API以返回504。
在查看Google devTools时,我可以看到调用已完成且状态为504.但是当我调试代码时,我得到的HttpErrorResponse状态为0。
我还设置了API以返回400响应,当我调试该代码时,响应状态为400.为什么400传播但504不传播?
我们正在使用Angular 6.0.6
更好的方法是实现错误处理程序。在我的例子中,我有一个公共类来进行HTTP调用,所有服务(例如:EmployeeService,SupplierService等)将与公共API通信以进行Rest API调用。下面是处理错误的示例代码。如果HTTP状态代码为404,您将看到以下内容。
服务器端错误 - 代码:404消息:http://localhost:5000/apiv1/account的Http失败响应:404 Not Found
这是我的Common Service的样子。
@Injectable({
providedIn: 'root'
})
export class ApiService {
getUrlvalue: string;
constructor(private http: HttpClient) { }
private formatErrors(error: any) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage=`Client side Error: ${error.error.message}`;
} else {
errorMessage=`Server side Error - Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(error.error);
}
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
//console.log(`${environment.api_url}${path}`);
this.getUrlvalue = `${environment.api_url}${path}`;
console.log('API service get request is making to : ' + this.getUrlvalue);
return this.http.get(this.getUrlvalue, { params }) //, { params }
.pipe(
catchError(this.formatErrors)
);
}
put(path: string, body: Object = {}): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body), httpHeaderOptions
).pipe(catchError(this.formatErrors));
}
post(path: string, body: Object = {}): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body), httpHeaderOptions
).pipe(catchError(this.formatErrors));
}
delete(path): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.delete(
`${environment.api_url}${path}`
).pipe(catchError(this.formatErrors));
}
}
从其他服务链接AccountService这是如何调用简单的HTTP Get
@Injectable({
providedIn: 'root'
})
export class AccountService {
// private http: HttpClient
constructor(private apiService: ApiService) { }
getAccounts(): Observable<Deal[]> {
return this.apiService.get('/account')
.pipe(
tap(deals => console.log('fetched Accounts 111111')),
catchError(this.handleError('getAccounts', []))
);
}
原来我们的API网关没有正确设置,我们没有返回正确的标头。
'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',