Can an Exception
object be converted into Json in Java 7?
For example:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
Can an Exception
object be converted into Json in Java 7?
For example:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
Yes, it is definitely feasible to achieve something similar to that. The key is not to convert the exception object itself, but rather extract and format the message it contains in a way you specify. Here's an example:
// […]
} catch (Exception ex) {
Gson gson = new Gson();
Map<String, String> exc_map = new HashMap<String, String>();
exc_map.put("message", ex.toString());
exc_map.put("stacktrace", getStackTrace(ex));
System.out.println(gson.toJson(exc_map));
}
The method getStackTrace()
can be implemented as described in this answer:
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
One approach is to iterate through the elements in a stack trace and create a structured output like:
{ "NullPointerException" :
{ "Exception in thread \"main\" java.lang.NullPointerException",
{
"Book.java:16" : "com.example.myproject.Book.getTitle",
"Author.java:25" : "at com.example.myproject.Author.getBookTitles",
"Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
}
},
"Caused By" :
{ "Exception in thread \"main\" java.lang.NullPointerException",
{
"Book.java:16" : "com.example.myproject.Book.getTitle",
"Author.java:25" : "at com.example.myproject.Author.getBookTitles",
"Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
}
}
}
To iterate over an exception, you can refer to this documentation:
catch (Exception cause) {
StackTraceElement elements[] = cause.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
System.err.println(elements[i].getFileName()
+ ":" + elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName() + "()");
}
}
Here is a structured method to convert an Exception into JSON:
public static JSONObject convertToJSON(Throwable e, String context) throws Exception {
JSONObject responseBody = new JSONObject();
JSONObject errorTag = new JSONObject();
responseBody.put("error", errorTag);
errorTag.put("code", 400);
errorTag.put("context", context);
JSONArray detailList = new JSONArray();
errorTag.put("details", detailList);
Throwable nextRunner = e;
List<ExceptionTracer> traceHolder = new ArrayList<ExceptionTracer>();
while (nextRunner!=null) {
Throwable runner = nextRunner;
nextRunner = runner.getCause();
detailObj.put("code", runner.getClass().getName());
String msg = runner.toString();
detailObj.put("message",msg);
detailList.put(detailObj);
}
JSONArray stackList = new JSONArray();
for (StackTraceElement ste : e.getStackTrace()) {
stackList.put(ste.getFileName() + ": " + ste.getMethodName()
+ ": " + ste.getLineNumber());
}
errorTag.put("stack", stackList);
return responseBody;
}
To see the full implementation of this conversion routine, you can visit the open-source library here: Purple JSON Utilities. This tool supports working with JSON Objects and exceptions.
The result will be in this JSON format:
{
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This structure aligns with the OASIS data standard OASIS OData, which is considered one of the most standardized options available, despite low adoption rates at present.
For more details on handling errors in JSON REST APIs, check out my blog post Error Handling in JSON REST API
Currently, I am delving into Java web development using Eclipse Kepler and have successfully obtained data from a method. This data is stored in both a ResultSet and a List<Object> within a jsp file. In PHP, there exists the handy print_r() function ...
I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...
I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...
Here is the code snippet I'm working with: package pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.safari.SafariDriver; public class MainPage { ...
Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...
Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...
Successfully working json response : obj = urllib.urlopen("http://www.omdbapi.com/?t=Fight Club") response_str = obj.read() response_json = simplejson.loads(response_str) The code above is making a successful json request that looks like : { "Title" ...
Recently, I've been experimenting with the functionality of this interesting website at . One challenge I encountered was the need for my program to automatically press a toggle button (which toggles the sidebar content visibility) in case manual inte ...
I received the following output from a JSON call in C#: {"Field": [ "PID", "PName"], "Data": [ [ 5, "A3"] ] } I am looking to extract only the Data part, which is an array of data, and store it in a DataTable. I need to do t ...
I am currently developing a website using Django and I am in need of a popup window that can display logging messages and automatically refresh itself every N seconds. In order to achieve this, I am utilizing the standard Python logger, JavaScript, and Daj ...
I am confused. I understand that Logstash allows us to input csv/log files and apply filters using separators and columns. The output is then sent to elasticsearch for use with Kibana. However, I'm unsure about whether or not we need to specify an ind ...
After attempting to parse a JSON file, I encountered an issue. When following the syntax for parsing, I received an error stating that the string cannot be converted into an array of dictionaries. However, after resolving this problem, it resulted in gener ...
A situation has arisen where I have properly set up Properties files and initialized the Webdriver object in a particular class. Now, my aim is to utilize this Webdriver object either within the same package or in another package. Can you guide me on how t ...
We have been using Selenium 2.5.2 for our Java tests, but now we believe it's time to upgrade to the latest version of Selenium (currently 3.14). After downloading Selenium 3.14 from https://www.seleniumhq.org/ and integrating it into our project, we ...
I have integrated the SwipeFlingAdapterView in my project to fetch data from a MySQL database. Here are the variables defined: private ArrayList<String> al; private ArrayAdapter<String> arrayAdapter; private int i; SwipeFlingAdapt ...
Hello, I'm looking for guidance on incorporating jquery with AJAX to fetch images from a JSON file and showcase them on my website. Below is the code snippet I have put together. function bookSearch(){ var search = document.getElementById('sea ...
I am in the process of generating a csv file containing user information. So far, I have successfully created a csv file for variables like "name," "surname," and age. However, I also have data stored in lists and dictionaries with unknown lengths that I d ...
I am attempting to integrate my custom vis component into the MainView VerticalLayout. However, it is appearing above the layout and the layout itself contains an empty component tag. Custom component code In this section, I have labeled my component as " ...
Is there a way to retrieve JSON data containing the names of top albums, artist names, and IDs from iTunes into PHP? https://itunes.apple.com/us/rss/topalbums/limit=10/json I attempted the following: <?php $content=file_get_contents("https://itunes.a ...
Currently, I am facing an issue while using Selenium WebDriver with TestNG in Eclipse. The problem arises when the page reloads midway for some data, and the timing of this reload is unpredictable. Due to this unpredictability, I am unable to apply an expl ...