如何从Angular 4/2中的后端读取自定义错误消息 [英] How to read Custom error message from backend in Angular 4/2

查看:378
本文介绍了如何从Angular 4/2中的后端读取自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

API

add(data) {
 return this.httpClient.post<any>('/api/v3/templates', data);
}

Observable

this.templateService.add(obj)

.subscribe(
 (response) => { 
  console.log(reposne)
 },
(error) => {
 console.log(error)
 }
);

我的Post API会返回一些消息错误,因为名称已经存在,但我无法响应导致错误打印到控制台的对象

My Post API gives back a error with some Message in response as Name Already Exists But i am not able to get that in error Object which is printed to console

The object which is printed is
{
    error:null
    headers:HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, 
    lazyInit: ƒ}
    message:"Http failure response for http://localhost/api/v3/templates: 
400 Bad Request"
    name:"HttpErrorResponse"
    ok:false
    status:400
    statusText:"Bad Request"
    url:"http://localhost/api/v3/templates"

}

由于错误
对象没有该响应主体,我如何获得正在响应的消息。

how can I get the message that I am getting in response as my error object doesn't have that response body.

推荐答案

返回的错误通常是HttpErrorResponse的实例,带有包含包装错误(客户端或服务器)的 error 属性

The error returned is normally an instance of HttpErrorResponse, with an error property containing the wrapped error (client or server)

https://angular.io/guide / http#getting-error-details

因此,通常情况下,您应该能够处理此类错误。

So normally you should be able to handle the error like this.

add(data) {
 return this.httpClient.post<any>('/api/v3/templates', data)
  .pipe(
      catchError(this.handleError)
    );
}

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an ErrorObservable with a user-facing error message
  return new ErrorObservable(
    'Something bad happened; please try again later.');
};

如果 error 属性为null,则可能是因为服务器未返回任何内容。您是否使用邮差或其他工具检查服务器是否返回了适当的响应?

If the error property is null this could be because the server does not return anything. Did you check using postman or some other tool that your server returns the appropriate response?

这篇关于如何从Angular 4/2中的后端读取自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆