尝试解析Observable返回的错误

时间:2019-01-04 20:10:46

标签: javascript json angular typescript

在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);
  }

1 个答案:

答案 0 :(得分: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);