ErrorHandler extends HttpServlet { public String createResponseMessage(HttpServletRequest request, HttpServletResponse response) { String responseMessage = "{\"errors\":[ "; String message = (String) request.getAttribute("javax.servlet.error.message"); Integer code = (Integer) request.getAttribute("javax.servlet.error.status_code"); Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); log.info("message: " + message + " code: " + code + " "); if (throwable != null) { throwable.printStackTrace(); if (throwable instanceof APIException) { message = ((APIException) throwable).getPublicMessage(); code = ((APIException) throwable).getCode(); response.setStatus(((APIException) throwable).getHttpCode()); } else if (throwable instanceof ServletException) { Throwable throwable1 = ((ServletException) throwable).getRootCause(); String cause = throwable1 != null ? throwable1.getCause().toString() : throwable.toString(); ErrorCode errorCode = ErrorCode.find(cause); code = errorCode.getCode(); String finalMessage = throwable1 != null ? throwable1.getCause().getMessage() : throwable.toString(); message = errorCode.getPublicMessage() + "# " + finalMessage; response.setStatus(errorCode.getHttpCode()); } else { ErrorCode errorCode = ErrorCode.find(throwable.getMessage()); code = errorCode.getCode(); message = errorCode.getPublicMessage(); if (errorCode == ErrorCode.INFRASTRUCTURE) { String message2 = throwable.getMessage().replace("\"", "\\\""); responseMessage += "{\"message\":\"" + message2 + "\",\"code\":1000},"; } response.setStatus(errorCode.getHttpCode()); } } if ((message == null) || message.isEmpty()) { ErrorCode errorCode = ErrorCode.DEFAULT; code = errorCode.getCode(); message = errorCode.getPublicMessage(); response.setStatus(errorCode.getHttpCode()); } responseMessage += "{\"message\":\"" + message + "\",\"code\":" + code + "}]}"; return responseMessage; }  void doGet(HttpServletRequest request, HttpServletResponse response); String createResponseMessage(HttpServletRequest request, HttpServletResponse response); void doPost(HttpServletRequest request, HttpServletResponse response);  }
@Test public void shouldReturnResponseWithValidErrorJSONWithoutMessage() throws IOException { ErrorHandler errorHandler = new ErrorHandler(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getAttribute("javax.servlet.error.message")).thenReturn(""); when(request.getAttribute("javax.servlet.error.status_code")).thenReturn(200); String message = errorHandler.createResponseMessage(request, response); assertNotNull(message); assertEquals("{\"errors\":[ {\"message\":\"Internal PaasManager Server error\",\"code\":500}]}", message); verify(response).setStatus(500); }