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.


Our Custom ErrorController

public class MyCustomErrorController implements ErrorController {

  private ErrorAttributes errorAttributes;

  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) -> {

      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());

  public String getErrorPath() {
      return "/error";

An application Controller

public class MyAppController {

  public void handleRequest() {
      throw new RuntimeException("test exception");

Boot main class

public class SpringBootMain{

  public static void main(String[] args) {;


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

    See Also