Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send error message as JSON object

I have two servlet: first servlet is similar to a client and creates an HttpURLConnection to call the second servlet.

I would like send a special error, formatted like a JSON object, so I call sendError method in this way:

response.sendError(code, "{json-object}") 

But in the first servlet when I read error with getResponseMessage method I just get standard HTTP message and not my json object as a string.

How I can get my json string?

like image 740
pAkY88 Avatar asked May 27 '10 21:05

pAkY88


People also ask

How do I send a JSON message?

Send JSON Data from the Client SideCreate a JavaScript object using the standard or literal syntax. Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request.

What is a JSON error message?

Overview. In cases where a JavaScript Object Notation (JSON) transaction fails, the API Gateway can use a JSON Error to convey error information to the client. By default, the API Gateway returns a very basic fault to the client when a message filter has failed.

How will you handle the error in JSON?

Instead of using the JSON Error filter, you can use the Generic Error filter to transform the JSON error message returned by applying an XSLT stylesheet.

Does mysql return JSON?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.


1 Answers

From the HttpServletResponse#sendError() javadoc:

The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.

So with this approach you have no other option than extracting the message from the HTML response yourself. JSoup may however be useful in this.

To achieve what you want, you need to set the error code and write the response yourself, e.g.

response.setStatus(code); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); 

Instead of code you could by the way also use one of the HttpServletResponse.SC_XXX constants for this.

like image 92
BalusC Avatar answered Sep 17 '22 02:09

BalusC