/** * Customized ErrorAttribute bean. * We really need to find a cleaner way of handling these error messages. * * @return customized ErrorAttributes */ @Bean public ErrorAttributes errorAttributes() { return new DefaultErrorAttributes() { @Override public Map<String, Object> getErrorAttributes( final RequestAttributes requestAttributes, final boolean includeStackTrace) { Map<String, Object> attributes = super .getErrorAttributes(requestAttributes, includeStackTrace); Throwable error = getError(requestAttributes); if (error instanceof MethodArgumentNotValidException) { MethodArgumentNotValidException ex = ((MethodArgumentNotValidException) error); attributes.put("errors", ex.getMessage()); } return attributes; } }; }
@Test public void filterHasError() { this.filter.setErrorAttributes(new DefaultErrorAttributes()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(500); request.setAttribute("javax.servlet.error.exception", new IllegalStateException("Foo")); response.addHeader("Content-Type", "application/json"); Map<String, Object> trace = this.filter.getTrace(request); this.filter.enhanceTrace(trace, response); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) trace.get("error"); System.err.println(map); assertThat(map.get("message").toString()).isEqualTo("Foo"); }
@Test public void filterHasError() { this.filter.setErrorAttributes(new DefaultErrorAttributes()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(500); request.setAttribute("javax.servlet.error.exception", new IllegalStateException("Foo")); response.addHeader("Content-Type", "application/json"); Map<String, Object> trace = this.filter.getTrace(request); this.filter.enhanceTrace(trace, response); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) trace.get("error"); System.err.println(map); assertEquals("Foo", map.get("message").toString()); }
@Bean public ErrorAttributes customizeErrorResponseAttributes() { return new DefaultErrorAttributes(){ @Override public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace); errorAttributes.remove("timestamp"); errorAttributes.remove("exception"); return errorAttributes; } }; }
@Autowired public ErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError()); }
@Bean @ConditionalOnMissingBean public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); }