I am not able to override default spring boot error response in REST api. I have following code
@ControllerAdvice
@Controller
class ExceptionHandlerCtrl {
@ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Invalid data")
@ExceptionHandler(BusinessValidationException.class)
@ResponseBody
public ResponseEntity<BusinessValidationErrorVO> handleBusinessValidationException(BusinessValidationException exception){
BusinessValidationErrorVO vo = new BusinessValidationErrorVO()
vo.errors = exception.validationException
vo.msg = exception.message
def result = new ResponseEntity<>(vo, HttpStatus.UNPROCESSABLE_ENTITY);
result
}
Then in my REST api I am throwing this BusinessValidationException. This handler is called (I can see it in debugger) however I still got default spring boot REST error message. Is there a way to override and use default only as fallback? Spring Boot version 1.3.2 with groovy. Best Regards
Remove
@ResponseStatus
from your method. It creates an undesirable side effect and you don't need it, since you are settingHttpStatus.UNPROCESSABLE_ENTITY
in yourResponseEntity
.From the JavaDoc on
ResponseStatus
:I suggest you to read this question: Spring Boot REST service exception handling
There you can find some examples that explain how to combine ErrorController/ ControllerAdvice in order to catch any exception.
In particular check this answer:
https://stackoverflow.com/a/28903217/379906
You should probably remove the annotation @ResponseStatus from the method handleBusinessValidationException.
Another way that you have to rewrite the default error message is using a controller with the annotation @RequestMapping("/error"). The controller must implement the ErrorController interface.
This is the error controller that I use in my app.