Spring Boot - Mapping /error to a custom controller by implementing ErrorController

[Updated: Mar 8, 2018, Created: Mar 7, 2018]

By default Spring Boot maps /error to BasicErrorController which populates model with error attributes and then returns 'error' as the view name to map application defined error pages.

To replace BasicErrorController with our own custom controller which can map to '/error', we need to implement ErrorController interface.


The Controller

public class MyAppController {

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

Implementing ErrorController

public class MyCustomErrorController implements ErrorController {

  public String handleError(HttpServletRequest request) {
      Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
      Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
      return String.format("<html><body><h2>Error Page</h2><div>Status code: <b>%s</b></div>"
                      + "<div>Exception Message: <b>%s</b></div><body></html>",
              statusCode, exception==null? "N/A": exception.getMessage());

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

Also check out Servlet - Error Handling tutorial to know what low level servlet error attributes can be used in our controller.


To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

We can also run the main method from our IDE.

Accessing unmapped URL:

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

Boot Implementing Custom Error Controller Example Select All Download
  • boot-custom-error-controller
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also