I have a spring boot rest API project and I am pondering how to change the default error object returned from spring boot.
UseCase: /token api is to be called witho
The exceptions from Servlet Filter which do not reach the controller are handled by
BasicErrorController
.
You need to override the BasicErrorController
to change the default exception body thrown by spring.
How to override:
@RestController
@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);
/*
If you want to pull default error attributes and modify them, use this
Map<String, Object> defaultErrorAttributes = this.getErrorAttributes(request, false);
*/
Map<String, Object> errorCustomAttribute = new HashMap<>();
errorCustomAttribute.put("status", "error");
errorCustomAttribute.put("message", status.name());
return new ResponseEntity(errorCustomAttribute, status);
}
@Override
public String getErrorPath() {
return "/error";
}
}
How error response will look like
{
"message": "UNAUTHORIZED",
"status": "error"
}