Java: set error header in servlet
When something goes wrong in the servlet, here is how to set the error header.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { // Try something that can go wrong.. } catch (Exception exception) { // Make sure to LOG the exception ... // Then report back something the client can use.. String message = "Bad error: reason....."; response.setHeader("status", message); response.setStatus(500); out.print(message); } }
In the client code, Javascript can be used to access the error status itself and the error message on the request object as request.getResponseHeader("status");
and request.status;
respectively. I don't cover here how the Javascript gets the request object.
Comments