我的错误消息如下所示:
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"}
}
}
或
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":"Message 2",
"exceptionType":"System.Data.Entity.Core.UpdateException",
}
}
任何人都可以给我一个关于如何从这两个JSON字符串中获取innerException消息的建议。问题是有时只有一个内部异常而另外两个异常。我需要的是从“innerException”
的最内部提取消息的一些方法答案 0 :(得分:5)
只需一个简单的循环即可:
var item = data;
while(item.innerException !== undefined) {
item = item.innerException;
}
var msg = item.message;
答案 1 :(得分:1)
您也可以使用递归解决方案:
function getMostInnerMessage(json) {
if (json.innerException){
return getMostInnerMessage(json.innerException);
}
else{
return json.message;
}
}
答案 2 :(得分:0)
轻松使用三行并扩展Object
类型:
/**
* 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
};
现在,您可以调用Object
方法的最后一个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());
请参阅jsfiddle:http://jsfiddle.net/t6j3ecp8/2/