I have this REST Controller that should also handle exceptions.
The @ExceptionHandler(MultipartException.class)
annotation is not working as explained.
So I am implementing HandlerExceptionResolver
which is basically working but is not as handy for REST and JSON responses as @ExceptionHandler
would be.
I would like to return my custom class ValidationReport
in resolveException
similar to the @ExceptionHandler handleBadRequest
. I was not able to create a ModelAndView with a ValidationReport
json response. Any Idea how I can combine both styles?
@RestController
class ValidationController implements HandlerExceptionResolver{
static Logger LOG = LoggerFactory.getLogger(ValidationController.class);
@RequestMapping(value="/validate", method=[POST])
public ValidationReport validate(MultipartFile file) {
LOG.info("received file ${file?.name}")
ValidationReport report = new ValidationReport();
return report
}
@ResponseStatus(BAD_REQUEST)
@ExceptionHandler(MultipartException.class)
@ResponseBody ValidationReport handleBadRequest(HttpServletRequest req, Exception ex) {
return new ValidationReport(USER_ERROR, "you should not upload files bigger then xx MB")
}
@Override
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof MultipartException){
response.sendError(BAD_REQUEST.value(),ex.message)
}
return null
}
}
I
This is not a solution I am not really happy with but one that works. I implement the HandlerExceptionResolver
Interface to catch all exceptions.
In the implemented Method I handle only the exception I am interested in. Then I send the caller a error code and tell him what he did wrong.
@Override
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof MultipartException){
response.sendError(413,"Content is to big. Maximal allowed request size is: ${Application.MAX_REQUEST_SIZE}")
}
}