HttpExceptionUtils { public static void createServletExceptionResponse( HttpServletResponse response, int status, Throwable ex) throws IOException { response.setStatus(status); response.setContentType(APPLICATION_JSON_MIME); Map<String, Object> json = new LinkedHashMap<String, Object>(); json.put(ERROR_MESSAGE_JSON, getOneLineMessage(ex)); json.put(ERROR_EXCEPTION_JSON, ex.getClass().getSimpleName()); json.put(ERROR_CLASSNAME_JSON, ex.getClass().getName()); Map<String, Object> jsonResponse = new LinkedHashMap<String, Object>(); jsonResponse.put(ERROR_JSON, json); Writer writer = response.getWriter(); JsonSerialization.writer().writeValue(writer, jsonResponse); writer.flush(); }  static void createServletExceptionResponse(
      HttpServletResponse response, int status, Throwable ex); static Response createJerseyExceptionResponse(Response.Status status,
      Throwable ex); @SuppressWarnings("unchecked") static void validateResponse(HttpURLConnection conn,
      int expectedStatus); static final String ERROR_JSON; static final String ERROR_EXCEPTION_JSON; static final String ERROR_CLASSNAME_JSON; static final String ERROR_MESSAGE_JSON; }
@Test public void testCreateServletException() throws IOException { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.getWriter()).thenReturn(printWriter); int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; Exception ex = new IOException("Hello IOEX"); HttpExceptionUtils.createServletExceptionResponse(response, status, ex); Mockito.verify(response).setStatus(status); Mockito.verify(response).setContentType(Mockito.eq("application/json")); ObjectMapper mapper = new ObjectMapper(); Map json = mapper.readValue(writer.toString(), Map.class); json = (Map) json.get(HttpExceptionUtils.ERROR_JSON); Assert.assertEquals(IOException.class.getName(), json.get(HttpExceptionUtils.ERROR_CLASSNAME_JSON)); Assert.assertEquals(IOException.class.getSimpleName(), json.get(HttpExceptionUtils.ERROR_EXCEPTION_JSON)); Assert.assertEquals("Hello IOEX", json.get(HttpExceptionUtils.ERROR_MESSAGE_JSON)); }