Nit*_*mar 12 javascript angular angular-httpclient
我在我的 Angular 应用程序中创建了一个 REST API 调用来下载一个文件。
我将 responseType 设置为 'blob' 因为我期待一个文件作为响应。
但是当服务器上没有可用的文件时,响应的错误代码为 404,即错误请求,正文中有一些消息。
但是我无法解析来自正文的错误消息,因为 HttpErrorResponse 在 error.error 中给出了一个 blob 对象
如何从错误对象而不是 blob 中获取实际主体。
还有什么方法可以配置 angular,在 api 调用成功时解析 blob 中的请求,否则解析 json 中的请求???
希望得到解决
小智 11
尝试这个
if(error.error instanceof Blob) {
error.error.text().then(text => {
let error_msg = (JSON.parse(text).message);
console.log(error_msg)
});
} else {
//handle regular json error - useful if you are offline
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试一个单独的错误处理函数,它返回响应如下
T-
public handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
Run Code Online (Sandbox Code Playgroud)
然后只需使用它来跟踪您的请求中的错误,如下所示 -
return this.http.post(this.appconstants.downloadUrl, data, { responseType: 'blob' }).pipe(
map(this.loggerService.extractFiles),
catchError(this.loggerService.handleError<any>('downloadFile')) // <----
);
Run Code Online (Sandbox Code Playgroud)
仅供参考,我上面用来返回文件的函数extractFiles如下 -
public extractFiles(res: Blob): Blob{
return res;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14516 次 |
| 最近记录: |