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