DEV Community

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

Posted on • Edited 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
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
@Slf4j
public class BasicErrorControllerOverride extends AbstractErrorController {

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

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

  @Override
  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.

Read more: 👇

Top comments (0)