我正在尝试将错误从我的API传递到Angular 4应用程序。问题是在角度方面我没有看到正确的错误消息:
Web Api错误产生如下:
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Headers = {{"errorMessage", "Message in header"}},
Content = new StringContent("Message in body")
}
);
我的角度代码类似于:
return this._http.get<IMyObj[]>(this._serviceUrl)
.do(this.handleSuccessResponse)
.catch(this.handleErrorResponse);
protected handleErrorResponse(err: HttpErrorResponse) {
console.info(err);
// some logic based on code
}
问题在于,如果我检查错误,那么错误&#34; property为null,message为&#34; url的响应失败&#34;并且没有自定义标头,但是在浏览器的网络选项卡上,我可以看到我的自定义标头有错误以及正文中的错误。如何从我的角度应用程序访问任何此消息?
答案 0 :(得分:2)
我的错误处理程序如下所示:
private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = '';
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = `An error occurred: ${err.error.message}`;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return Observable.throw(errorMessage);
}
请注意,它使用status
和message
属性,而不是error
属性。
答案 1 :(得分:0)
您可以尝试一下。
在此,我传递了一个搜索值。您甚至可以尝试不这样做。
// Service.ts
import {catchError, map, tap } from 'rxjs/operators';
import {throwError} from 'rxjs';
import { HttpClient, HttpErrorResponse} from '@angular/common/http';
private employeeUrl="https://api.employee.new/dept/value.json?search=city:"
getdata(selectedtype): Observable<employee[]> {
return this.http.get<employee[]>(this.employeeUrl+selectedtype)
.pipe(
catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse)
{
return throwError(error.message || 'Server Error')
}
//employeecomponent.ts
employeedata:any=[];
public errorMsg;
ngOnInit(){
this.dataService.getdata(this.search).subscribe(data =>this.employeedata=data,
error =>this.errorMsg=error);
}
//最后,您可以将其绑定到HTML文件中
// employeecomponent.html
<h3>errorMsg</h3>