DEV Community

Cover image for How to update the default exception body thrown by Sping-Boot

Posted on • Updated on

How to update the default exception body thrown by Sping-Boot

The default exception in spring, if thrown (and not handled by ControllerAdvice) follows the exception format as

    "timestamp": "2020-06-14T05:46:37.538+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/path_requested" 

To change this default exception body to return your own custom fields, you just have to override the BasicErrorController(provided by the framework) and its error method.

  • How to override
public class BasicErrorControllerOverride extends AbstractErrorController {

  public BasicErrorControllerOverride(ErrorAttributes errorAttributes) {

  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    HttpStatus status = this.getStatus(request);
    Map<String, Object> errorCustomAttribute = new HashMap<>();
    errorCustomAttribute.put("custome_message", "error");
    return new ResponseEntity(errorCustomAttribute, status);

  public String getErrorPath() {
    return "/error";
  • How the error will now look like:
    "custome_message": "UNAUTHORIZED",
    "custom_status_field": "error"

🍻 If you enjoyed this story, please click the ❤️ button and share it to help others find it! Feel free to leave a comment below.


Top comments (0)