ErrorResponses { static List<StackTraceRepresentation> buildExceptionContext(Throwable cause) { List<StackTraceRepresentation> stackTraces = new ArrayList<>(); for (Throwable currentCause = cause; currentCause != null; currentCause = currentCause.getCause()) { stackTraces.add(new StackTraceRepresentation(currentCause)); } return stackTraces; } private  ErrorResponses(); static ErrorResponse noRequestBody(HttpServletRequest httpServletRequest); static ErrorResponse badRequest(HttpServletRequest httpServletRequest, String message); static ErrorResponse badRequest(HttpServletRequest httpServletRequest, String message, Exception cause); static ErrorResponse badRequest(HttpServletRequest httpServletRequest, Exception cause); static ErrorResponse internalServerError(HttpServletRequest httpServletRequest, Exception cause); static void sendError(HttpServletResponse httpServletResponse, ErrorResponse.ErrorResponseBuilder errorResponseBuilder); static void sendError(HttpServletResponse httpServletResponse, ErrorResponse errorResponse); static Map<String, Object> buildWebRequestContext(WebRequest webRequest);  }
@Test public void testBuildOfGenericException() { List<ErrorResponses.StackTraceRepresentation> mappedError; try { throw new IOException("simulated I/O error"); } catch (IOException e) { mappedError = ErrorResponses.buildExceptionContext(e); } assertThat(mappedError, is(hasSize(1))); }
@Test public void testBuildOfJacksonWithInvalidType() throws Exception { String badDocument = "{\"value\":\"notANumber\"}"; List<ErrorResponses.StackTraceRepresentation> mappedError = null; try { mapper.readValue(badDocument, MyService.class); fail("Expected parsing exception"); } catch (InvalidFormatException e) { mappedError = ErrorResponses.buildExceptionContext(e); } Map<String, Object> details = mappedError.get(0).getDetails(); assertThat(details, is(notNullValue())); assertThat(details.get("pathReference"), is(equalTo(this.getClass().getName() + "$MyService[\"value\"]"))); assertThat(details.get("targetType"), is(equalTo("int"))); assertThat((String) details.get("errorLocation"), containsString("line: 1")); assertThat(details.get("document"), is(equalTo("{\"value\":\"notANumber\"}"))); }
@Test public void testBuildOfJacksonWithInvalidPropertyName() throws Exception { String badDocument = "{\"myType\":\"myServiceType\"}"; List<ErrorResponses.StackTraceRepresentation> mappedError = null; try { mapper.readValue(badDocument, MyService.class); fail("Expected parsing exception"); } catch (PropertyBindingException e) { mappedError = ErrorResponses.buildExceptionContext(e); } ErrorResponses.StackTraceRepresentation stackTrace = mappedError.get(0); assertThat(stackTrace.getDetails(), is(notNullValue())); assertThat(stackTrace.getDetails().get("property"), is(equalTo("myType"))); }