试图解析从Observable返回的错误

问题描述 投票:0回答:1

在Angular 7中,我正在调用我们的MS WebApi并收到一个错误响应,我似乎无法解析它。原始响应如下所示:

"{"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."}"

错误响应作为对象返回:

 error.error

JSON.parse(error.error)抛出一个JSON错误Unexpected token in JSON at position 242

拉出MessageMessageDetail房产最干净的方法是什么?

我的错误处理程序如下:

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

    
    console.log(err);    
    return throwError(err);
  }
javascript json angular typescript
1个回答
1
投票

似乎问题是JSON字符串包含一些新的行字符。

你可以用空格替换那些,这是一个例子:

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);
© www.soinside.com 2019 - 2024. All rights reserved.