Close

Spring Boot - Returning JSON Response from Custom ErrorController

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

Following example shows how to return JSON error response from our custom ErrorController. In this example we are going to extend AbstractErrorController (an abstract implementation of ErrorController) which provides various helper methods.

Example

Our Custom ErrorController

@Controller
public class MyCustomErrorController extends AbstractErrorController {

  public MyCustomErrorController(ErrorAttributes errorAttributes) {
      super(errorAttributes);
  }

  @RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  public Map<String, Object> handleError(HttpServletRequest request) {
      Map<String, Object> errorAttributes = super.getErrorAttributes(request, true);
      return errorAttributes;
  }

  @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

Also check out returning XML error response from ErrorController.

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

Returning JSON Response from Custom ErrorController Select All Download
  • boot-produce-error-in-json
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also