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?