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.


Our Custom ErrorController

public class MyCustomErrorController extends AbstractErrorController {

  public MyCustomErrorController(ErrorAttributes errorAttributes) {

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

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


Also check out returning XML error response from ErrorController.

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

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

See Also