4

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?

Naanavanalla
  • 1,412
  • 2
  • 27
  • 52
  • Did you tried something like this? `@Size( max = 40, message = "Title should be max 40 characters" )` When you read message from exception, it would be containing this message, I guess... But not sure :) – oxyt Jan 14 '20 at 11:12
  • 1
    The `eventRequestBean` is the argument that isn't valid. The `MethodArgumentNotValidException` contains a `BindingResult` which contains all errors for all the fields or globally. – M. Deinum Jan 14 '20 at 11:25
  • `BindingResult` has a field errors which has the required details, but no getters available to access it – Naanavanalla Jan 14 '20 at 12:00
  • @oxyt I added the message, but how to get it now? – Naanavanalla Jan 14 '20 at 12:03
  • I could get it from the `BindingResult`. Thank You @M.Deinum – Naanavanalla Jan 14 '20 at 12:21

1 Answers1

2
@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.

Naanavanalla
  • 1,412
  • 2
  • 27
  • 52