Spring Boot - Using ErrorAttributes in our custom ErrorController

[Updated: Mar 8, 2018, Created: 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-starter-web 2.0.0.RELEASE: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container [Description from spring-boot-starter-web-2.0.0.RELEASE.pom]
    Corresponding Spring version: 5.0.4.RELEASE
  • 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