在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
。
拉出Message
和MessageDetail
房产最干净的方法是什么?
我的错误处理程序如下:
protected handleError(error: HttpErrorResponse) {
let err = (error && error.message !== undefined) ? error.message : '';
console.log(err);
return throwError(err);
}
似乎问题是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);