What is the best way to extract an inner exception message from a JSON string using JavaScript?

I am struggling with error messages that have a nested structure like this:

var data = 
{"message":"An issue has occurred.",
 "exceptionMessage":"An error occurred while updating the entries. Refer to the inner exception for more details.",
 "exceptionType":"System.Data.Entity.Infrastructure.DbUpdateException",
 "innerException":{
    "message":"An issue has occurred.",
    "exceptionMessage":"An error occurred while updating the entries. Refer to the inner exception for more details.",
    "exceptionType":"System.Data.Entity.Core.UpdateException",
    "innerException":{
         "message":"An issue has occurred.",
         "exceptionMessage":"Message 1"}
  }
}

or

var data = 
{"message":"An issue has occurred.",
 "exceptionMessage":"An error occurred while updating the entries. Refer to the inner exception for more details.",
 "exceptionType":"System.Data.Entity.Infrastructure.DbUpdateException",
 "innerException":{
    "message":"An issue has occurred.",
    "exceptionMessage":"Message 2",
    "exceptionType":"System.Data.Entity.Core.UpdateException",
  }
}

Can someone assist me in finding a way to extract the message from the innermost "innerException" in these two JSON strings? It's challenging due to the varying number of inner exceptions. I need a solution to retrieve the message from the most inside "innerException".

Answer №1

To solve this issue, you can implement a basic loop like this:

let current = data;
while(current.innerException !== undefined) {
   current = current.innerException;
}
let errorMessage = current.message;

Answer №2

An alternative approach would be to implement a recursive method:

function findDeepestErrorMessage(data) {
    if (data.innerError){
        return findDeepestErrorMessage(data.innerError);
    }
    else{
        return data.errorMessage;
    }
}

Answer №3

A simple solution with just three lines of code that extends the Object type:

/**
* Retrieve the innermost exception for ALL objects.
**/
Object.prototype.getInnerException = function(){
    if( typeof this.innerException !== 'undefined ) // Check for innerException
        var innerException = this.innerException.getInnerException(); // Call recursively

    // You could throw an Exception if it's the first level and there is no innerException.

    return innerException || this; // Return the innermost exception or the current object
};

Now you have the ability to access the innermost exception by using the Object method:

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

Check out the jsfiddle example here: http://jsfiddle.net/t6j3ecp8/2/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a collection of SVG illustrations using Vivus.js

Is it possible to draw multiple SVGs using Vivus.js without having to call the function for each individual drawing? I've encountered an issue with the second drawing not animating properly. Any suggestions or experience with this? Check out this pen ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...

Discovering intersections between Polylines on Google Maps - a comprehensive guide

I'm currently developing a project involving a unique twist on Google Maps, focusing exclusively on natural hiking paths. My routes are built using GPX files converted into Google Maps polylines. Is there an efficient way to identify the intersection ...

Issue with Firefox-Android causing dropdown toggle to malfunction

When I manually trigger a dropdown, it closes when any click is performed outside of it (while open). This code works in all browsers except for Firefox on Android. Why does this happen? It seems like the event parameter doesn't reach the function ...

Tips for CSS: Preventing onhover animation from resetting with each hover

I've created an on-hover CSS animation that smoothly transitions between images. However, I encountered a lagging issue when the user quickly hovers over SECTION ONE and SECTION TWO before the animation ends, causing the animation to restart and lag. ...

Exploring Laravel Relationship Joins for JSON Data

In my Laravel project, I am utilizing Eloquent Relationships to transform my data into JSON format. The challenge I'm facing is that the Eloquent Relations are being displayed within JSON as an object, whereas I need a JSON output with variables direc ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

Can Apache Camel automatically convert JSON to POJO data types?

Is it possible to configure Camel in such a way that it can automatically handle data type conversions from JSON to a POJO? For instance, consider the following JSON example found on Camels website: { "id" : 123, "first_name" : "Donald", "l ...

Ways to extract input values from a specific row in a textbox as users input data

On a button click, I am dynamically adding data to an HTML table using the loadbooks function. When the user clicks on the button, the table is populated with data. <button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ...

Cross domain requests with jQuery's getJSON function

Struggling to fetch data using jQuery Cross Domain from GitHub, but hitting a roadblock! I've come across suggestions to use jsonp requests, but can't seem to figure out what's going wrong. http://jsfiddle.net/jzjVh/ Chrome seems to be int ...

Access the Body Content of a Post Using Laravel

After sending a raw body content from Postman to Laravel: { "id" : "123456789" "jsonrpc": "2.0", "params" : { "loginId" : "24319915347", "password" : "avc", } } Unfo ...

React Router - Implementing a <Redirect> element rather than a list of child components

Here is the code snippet I am working with: import { Redirect } from 'react-router-dom'; import QPContent from '../QPContent'; class AnswerContainer extends Component { constructor(props) { super(props); this.state = { ...

What does the "listen EACCESS localhost" error in the code signify and why is it occurring?

const express = require('express'); const morgan = require('morgan'); const host = 'localhost'; const port = 3000; const app = express(); app.use(morgan('dev')); app.use(express.static(__dirname + '/public&ap ...

Transform JSON data into a C# class with dual Dictionary attributes

Currently, I am in the process of creating an app using Xamarin and I have a straightforward JSON file consisting of objects that I want to deserialize all at once into my C# Class within my domain. (I am relying on the Newtonsoft Json.NET Framework) Each ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Error: Cannot access the length property of an undefined value in the JEST test

I'm currently working on incorporating jest tests into my project, but I encountered an error when running the test. The issue seems to be related to a missing length method in the code that I am attempting to test. It appears to be originating from s ...

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

Encountering an error with [object%20Object] when utilizing ajaxFileUpload

I wrote a JavaSscript script that looks like this: $.ajaxFileUpload({ url: url, secureuri: false, fileElementId: ['upload-file'], dataType: "JSON", data:{ "sample_path":$(".demo-view-container-left .vie ...

Is it necessary to use preg_replace on a JSON string in order to prevent null values when using json_decode?

Dealing with an outdated system that sends JSON data has caused me some trouble. I encountered a bug where using json_decode( $json_string, true); would result in returning null. After much frustration, I stumbled upon the solution here, which advised to ...

Asp.net Core 3.1: Understanding the Maximum Character Limit for JSON Objects

It's been a couple of years since this question was asked, but I'm still struggling with the issue and haven't found a solution yet. Is there any way to limit the size of JSON objects in Asp.net Core 3.1? I've tried looking for solution ...