bob.mazzo
bob.mazzo

Reputation: 5637

Trying to parse an error returned from an Observable

In Angular 7, I'm calling into our MS WebApi and receiving an error response which I cannot seem to parse out properly. The raw response looks like this:

"{"Message":"Add System Instance Failed", "MessageDetail":"2; Cannot insert duplicate key row in object 'dbo.SystemInstanceTbl' with unique index 'IX_SystemInstanceTbl'. The duplicate key value is (The_Duplicate_Value).
The statement has been terminated.", "ErrorCode":"50105952", "Exception":"System.ServiceModel.FaultException`1[Objects.FaultDetail]: Add  System Instance Failed."}"

The error response comes back as object:

 error.error

But JSON.parse(error.error) throws a JSON error Unexpected token in JSON at position 242.

What's the cleanest way to pull out the Message and MessageDetail properties ?

My error handler is as follows :

protected handleError(error: HttpErrorResponse) {    
    let err = (error && error.message !== undefined) ? error.message : '';  

    
    console.log(err);    
    return throwError(err);
  }

Upvotes: 0

Views: 447

Answers (1)

Titus
Titus

Reputation: 22474

It seems that the problem is that the JSON string contains some new line characters.

You can replace those with spaces, here is an example:

let jsonStr = `{"Message":"Add System Instance Failed", "MessageDetail":"2; Cannot insert duplicate key row in object 'dbo.SystemInstanceTbl' with unique index 'IX_SystemInstanceTbl'. The duplicate key value is (The_Duplicate_Value).
The statement has been terminated.", "ErrorCode":"50105952", "Exception":"System.ServiceModel.FaultException\`1[Objects.FaultDetail]: Add  System Instance Failed."}`;

jsonStr = jsonStr.replace(/\n/g, " ");

const data = JSON.parse(jsonStr);
console.log(data);

Upvotes: 1

Related Questions