1

I am working on a REST backend and I have a requirement to send error information (messages together with custom application keys & codes) as JSON back to the front end.

I am not sure whether to include the JSON in the msg argument to the sendError method (from HttpServletResponse) as follows:

void sendError(int sc,
               java.lang.String msg)
               throws java.io.IOException

... or use the response's actual payload as follows:

response.getWriter().write(json);

Can anyone please advise as to which is the best way to proceed?

1 Answer 1

2

The sendError will set the content type to "text/html"and as such is not a good candidate for pushing custom json error messages to the client.

You're better off setting the statuscode yourself

response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

and then writing the JSON string you want using the writer.

This is obviously very low-level. If you're using some kind of REST framework it typically has good support for automatically translation exceptions into a JSON format. That way you simply need to throw an exception and the framework will do the rest.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this reply! Do you have a specific framework in mind for avoiding the low level drudge?
Spring is pretty good. (basic tutorial at spring.io/guides/gs/rest-service). You can customize the exception handling by providing custom ExceptionHandlers (spring.io/blog/2013/11/01/exception-handling-in-spring-mvc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.