I’m writing my first JAVA servlet and I have a question.
May be it’s important to say that my servlet will be called from Google Web Toolkit (AJAX)
First thing that I do is to create PrintWriter and start to write in it my JSON output
PrintWriter out = response.getWriter();
...
out.println("[");
out.println(" {");
out.println(" \"validation\" : {");
...
but what will happened if meanwhile I get an error condition?
What is the right way to return an error to client? (AJAX client)
Do I have to buffer my output (HOW?) and return error as JSON (instead of output)
or
I have to throw ServletException?
Just build the string in memory using for example
StringBuilder. Do not write any character to the response yet until you’re finished building the string. That’s “buffering”.When something fails in meanwhile, either throw
ServletException(which will end up in a server default error page with status code 500), or useHttpServletResponse#sendError()to send a more specific error status. But generally, status code 500 is enough sign forXMLHttpRequestclient that something failed at the server side.