Mavericks
Mavericks

Reputation: 283

Preventing Boolean from Junk Value in Object in Rest API Call

I have one Object which has 3 attributes having Integer,String and Boolean Data type in Java,looks like below given REST Body.

 {
    "famousForId": 3,
    "name": "Food",
    "activeState": true
 }

i've one pojo class which looks like this

@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Document(collection="famousFor")
public class FamousFor {

//     @Id
     @NotNull
        @PositiveOrZero
     Long famousForId;
     @NotBlank(message = ApplicationUtil.MISSING_FIELD)
     @Pattern(regexp = "^[A-Za-z0-9]+$")
             @Pattern(regexp = "^[A-Za-z0-9]+$",message = "Name Can't Have Special Characters")
     String name;
     @NotNull(message = ApplicationUtil.MISSING_FIELD)
     Boolean activeState;
}

and my controller is handling errors properly any junk value for Long and String Value, however if we are passing junk value for Boolean it's without showing any error, it directly throws Http code 400 bad request, i want the proper message for this attribute as well,any help would be highly appreciated. I'm using Spring boot 2.0.6 My Controller looks something like the below given code block

 @RequestMapping(value="/saveFamousForDetails",produces={"application/json"},method=RequestMethod.POST)
    ResponseEntity<?> saveEssentialDetails(@ApiParam(value="Body Parameters") @RequestBody @Validated @ModelAttribute("famousFor") FamousFor famousFor, BindingResult bindingResult)throws Exception;

Upvotes: 0

Views: 692

Answers (1)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

One way I can think of is writing a ExceptionHandler class to your controller using @ControllerAdvice. Override "handleHttpMessageNotReadable" method.

@ControllerAdvice
@Log4j2
public class ExceptionHandler extends ResponseEntityExceptionHandler {

  @Override
  protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException exception,
      HttpHeaders headers, HttpStatus status, WebRequest request) {
    // log the error and return whatever you want to
  }

}

Upvotes: 1

Related Questions