Close

Spring Boot - Using ErrorAttributes in our custom ErrorController

[Last Updated: Mar 8, 2018]

Spring Boot provides ErrorAttributes interface which helps to extract the low level Servlet error attributes. We can inject ErrorAttributes as a bean in our custom ErrorController (last example). Spring boot provides only one implementation DefaultErrorAttributes, which provides various attributes as stated here.

Example

Our Custom ErrorController

@Controller
public class MyCustomErrorController implements ErrorController {

  @Autowired
  private ErrorAttributes errorAttributes;

  @RequestMapping("/error")
  @ResponseBody
  public String handleError(HttpServletRequest request) {
      ServletWebRequest servletWebRequest = new ServletWebRequest(request);
      Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(servletWebRequest, true);
      final StringBuilder errorDetails = new StringBuilder();
      errorAttributes.forEach((attribute, value) -> {
          errorDetails.append("<tr><td>")
                      .append(attribute)
                      .append("</td><td><pre>")
                      .append(value)
                      .append("</pre></td></tr>");
      });

      return String.format("<html><head><style>td{vertical-align:top;border:solid 1px #666;}</style>"
              + "</head><body><h2>Error Page</h2><table>%s</table></body></html>", errorDetails.toString());
  }

  @Override
  public String getErrorPath() {
      return "/error";
  }
}

An application Controller

@Controller
public class MyAppController {

  @RequestMapping("/")
  public void handleRequest() {
      throw new RuntimeException("test exception");
  }
}

Boot main class

@SpringBootApplication
public class SpringBootMain{

  public static void main(String[] args) {
      SpringApplication.run(SpringBootMain.class);
  }
}

Output

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.0.RELEASE
    Corresponding Spring Version 5.0.4.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

ErrorAttributes Example Select All Download
  • boot-error-controller-with-error-attribute
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyCustomErrorController.java

    See Also