gpt4 book ai didi

javascript - 尝试解析从 Observable 返回的错误

转载 作者:行者123 更新时间:2023-12-03 00:27:03 24 4
gpt4 key购买 nike

在 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错误意外的 token
JSON 中的位置 242

提取 MessageMessageDetail 属性的最简洁方法是什么?

我的错误处理程序如下:

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

关于javascript - 尝试解析从 Observable 返回的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54045402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com