如何使用Javascript从JSON字符串中获取内部异常消息?
我有如下错误消息:如何使用Javascript从JSON字符串中获取内部异常消息?,javascript,json,Javascript,Json,我有如下错误消息: var data = {"message":"An error has occurred.", "exceptionMessage":"An error occurred while updating the entries. See the inner exception for details.", "exceptionType":"System.Data.Entity.Infrastructure.DbUpdateException", "innerExcept
var data =
{"message":"An error has occurred.",
"exceptionMessage":"An error occurred while updating the entries. See the inner exception for details.",
"exceptionType":"System.Data.Entity.Infrastructure.DbUpdateException",
"innerException":{
"message":"An error has occurred.",
"exceptionMessage":"An error occurred while updating the entries. See the inner exception for details.",
"exceptionType":"System.Data.Entity.Core.UpdateException",
"innerException":{
"message":"An error has occurred.",
"exceptionMessage":"Message 1"}
}
}
或
有谁能给我一个建议,告诉我如何从这两个JSON字符串中获取innerException消息。问题是,有时只有一个内部异常,而另外两个内部异常。我需要的是从“innerException”的最内部提取消息的某种方法,只需一个简单的循环即可:
var item = data;
while(item.innerException !== undefined) {
item = item.innerException;
}
var msg = item.message;
您也可以使用递归解决方案:
function getMostInnerMessage(json) {
if (json.innerException){
return getMostInnerMessage(json.innerException);
}
else{
return json.message;
}
}
使用三行并扩展
对象
类型很容易:
/**
* Return the last innerException (more down) for ALL objects.
**/
Object.prototype.getInnerException = function(){
if( typeof this.innerException !== 'undefined' ) // Check if has a innerException
var innerException = this.innerException.getInnerException(); // Re-call
// You could throw a Exception if it's the first level and ir hasn't an innerException.
return innerException || this; // Return the the next innerException or the actual
};
现在,您可以获得对对象的最后一次innerException调用(更详细):
//Object {message: "An error has occurred.", exceptionMessage: "Message 1"}
console.log(data.getInnerException());
//Object {message: "An error has occurred.", exceptionMessage: "Message 2", exceptionType: "System.Data.Entity.Core.UpdateException"}
console.log(data2.getInnerException());
请参阅jsiddle:数据。innerException
或数据[“innerException”]
您需要一个递归函数或循环,添加了一个答案来说明循环,因为它可能更简单。这些不是JSON字符串。这些是对象文本,不需要再解析它们。您确定innerException
中的数据innerException
吗?@Praveen:是的,innerException可以继续包含更多的异常。不过,我还没有看过很多超过4级的文章。这篇文章被自动标记为低质量,因为没有解释这段代码摘录的作用。真的吗?!您是否要扩展对象类型以获得innerException这样的特定对象?它在99%的时间里都不适用,所以为什么它应该放在对象上呢?数据是对象
,需要内部异常
方法。您还可以执行其他类型,如CustomException,并将该方法添加到其中。您只需要在需要获取InterException
时进行扩展。正确的方法是为异常创建一个类型,但这不是这里的问题。如果你愿意,你可以把方法改成函数,虽然我不喜欢,但它是一样的。扩展对象原型是一个非常糟糕的主意。在大多数情况下,它是好的,但有一天它会回来咬你。扩展错误更好。
//Object {message: "An error has occurred.", exceptionMessage: "Message 1"}
console.log(data.getInnerException());
//Object {message: "An error has occurred.", exceptionMessage: "Message 2", exceptionType: "System.Data.Entity.Core.UpdateException"}
console.log(data2.getInnerException());