简体   繁体   中英

How can I access HTTP error response body in angular

I want to access error response body and show the message in that array

ERROR:
Bp {headers: Op, status: 422, statusText: "OK", url: "https://abc.trade/trade/save-trade", ok: false, …}
error: Array(1)
0:
  errorArgumentsMap: null
  errorCode: "CREATE_ERROR_CODE"
  errorPropagate: null
  fieldName: ""
  message: "trade already exists with id(T4)"
  name: ""
__proto__: Object
length: 1
__proto__: Array(0)
headers: Op {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for https://abc.trade/trade/save-trade: 422 OK"
name: "HttpErrorResponse"
ok: false
status: 422
statusText: "OK"
url: "https://abc.trade/trade/save-trade"

This is the response I get from API. Now I want to access error.error.message. Below is my code

---TS File---

this.createTrade.saveTrade(tradeData).subscribe((data: any)=>{       
        if(data.id){
          console.log('Created Sucessfully')          
        }        
      },
      error => {        
        if(error){
          let errorMsg = error.error.message;           
          console.log(errorMsg)
        }
      }
)

---service.ts---

saveTrade(request: any) {
const urlList = 'https://abc.trade/trade/save-trade';
return this.http
  .post<[]>(urlList, request, {
    headers: this.headers
  })
  .pipe(
    map(data => {
      return data;
    }),
    catchError(this.handleError)
  );   

}

On sucess it is working. But on error I'm not able to read error.error.message.I even tried accessing error.error[0].message. Could you guys please advise

在此处输入图像描述

did you try

saveTrade(request: any) {
const urlList = 'https://abc.trade/trade/save-trade';
return this.http
  .post<[]>(urlList, request, {
    headers: this.headers
  })
  .pipe(
    map(data => {
      return data;
    }),
    catchError(error => {
      return of(error);
})

  );   


in ts file =>

this.createTrade.saveTrade(tradeData).subscribe((data: any)=>{       
        if(data.id){
          console.log('Created Sucessfully')          
        }        
      },
      error => {      
          console.log(error)
      }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM