I am using javax.validation.Size
annotation to perform String size validation.
@Data
public class EventRequestBean {
@Size( max = 40 )
private String title;
@Size( max = 50 )
private String topic;
}
And I am using a global exception handler to throw the custom exception to the client-side.
@ExceptionHandler( { MethodArgumentNotValidException.class } )
public final ResponseEntity handleException( Exception e, WebRequest request )
{
if( e instanceof MethodArgumentNotValidException )
{
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
String parameterName = exception.getParameter().getParameterName();
// return buildError(new DataException(GeneralConstants.EXCEPTION, "Invalid content length: field +"e))
return null;
}
return null;
}
In my custom exception DataException
, the second argument is the error message. I want to set the field name and the valid size constraint as the message.
I am trying to get the field name from the exception thrown, but instead of giving me the name title
, it is giving me the parameter name eventRequestBean
I am using in the controller from where this exception is thrown.
@PostMapping( "/event" )
public ResponseEntity createEvent( @Valid @RequestBody EventRequestBean eventRequestBean )
{
try
{
log.info(GeneralConstants.LOGGER_CONSTANT,
" Entered create event controller, path:rest/events/event - POST");
userCommons.throwExceptionForOtherThanAdminUser(getLoggedInUser());
return buildResponse(eventService.addEvent(eventRequestBean, getLoggedInUser()));
}
catch( DataException e )
{
return buildError(e);
}
}
How can I get the field name and the set valid size so that I can create my own custom exception?
@ExceptionHandler( { MethodArgumentNotValidException.class } )
public final ResponseEntity handleException( Exception e, WebRequest request )
{
if( e instanceof MethodArgumentNotValidException )
{
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
StringBuilder errorMessage = new StringBuilder("");
for( ObjectError error : allErrors )
{
errorMessage.append(error.getDefaultMessage()).append(";");
}
return buildError(
new DataException(GeneralConstants.EXCEPTION, errorMessage.toString(), HttpStatus.BAD_REQUEST));
}
return null;
}
First, you need to provide the error message with the size constraint as follow,
@Data
public class EventRequestBean {
@Size( max = 40, message = "The value '${validatedValue}' exceeds the max limit of {max} characters" )
private String title;
@Size( max = 50, message = "The value '${validatedValue}' exceeds the max limit of {max} characters" )
private String topic;
}
Now, in the exception handler, you can access the error message by tapping to the exception's BindingResult
property as described above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With