我有一个对象,在Java中它具有3个具有Integer,String和Boolean Data类型的属性,如下图所示。
{
"famousForId": 3,
"name": "Food",
"activeState": true
}
我有一个像这样的pojo课
@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;
}
并且我的控制器正确地处理了Long和String Value的任何垃圾值的错误,但是,如果我们传递的是Boolean的垃圾值,则没有显示任何错误,它将直接引发Http代码400错误的请求,我想要正确的消息属性,任何帮助将不胜感激。 我正在使用Spring Boot 2.0.6 我的控制器看起来像下面给出的代码块
@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;
答案 0 :(得分:1)
我能想到的一种方法是使用@ControllerAdvice将ExceptionHandler类写入您的控制器。覆盖“ handleHttpMessageNotReadable”方法。
@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
}
}