Spring Boot provides errors in the json format like this:
JavaScript
x
{
"timestamp": "2019-01-17T16:12:45.977+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Error processing the request!",
"path": "/endpoint"
}
Is it possible for me to obtain this error inside the ErrorController
and to proceed with it?
JavaScript
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(Model model) {
// how to get json-error here?
model.addAttribute("resultJson", ?);
return "error";
}
}
Is it inside the HttpServletResponse
or maybe something else?
Advertisement
Answer
The default error
attributes are extracted from a WebRequest
using the ErrorAttributes
bean.
Spring already provided a default implementation of this bean, the DefaultErrorAttributes
bean.
You can have this bean injected by the container, as any usual bean, to your custom /error controller implementation so you can use it:
JavaScript
@Controller
@RequestMapping({"/error"})
public class CustomErrorController extends AbstractErrorController {
public CustomErrorController(final ErrorAttributes errorAttributes) {
super(errorAttributes, Collections.emptyList());
}
@RequestMapping
public String handleError(Model model, HttpServletRequest request) {
Map<String, Object> errorAttributes = this.getErrorAttributes(request, false); // retrieve the default error attributes as a key/value map (timestamp, status, error...)
// ...
}
@Override
public String getErrorPath() {
return "/error";
}
}
Update (by @Igorz)
As of Spring Boot version 2.3.0
JavaScript
org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes(HttpServletRequest, boolean, boolean, boolean)
has been deprecated in favor of:
JavaScript
org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes(HttpServletRequest, ErrorAttributeOptions)
Static factory ErrorAttributeOptions.defaults()
can be used as default ErrorAttributeOptions
argument of above method.