我的申请中有以下字段
@NotNull
@JsonDeserialize(using = LocalDateDeserializer.class)
@Schema(description = "BIRTH DATE", example = "1992-02-15")
private LocalDate birthDate;
所以我设置了以下杰克逊解串器:
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
protected LocalDateDeserializer() {
super(LocalDate.class);
}
@Override
public LocalDate deserialize(
final JsonParser jsonParser,
final DeserializationContext deserializationContext)
throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
String date = node.asText();
try {
return LocalDate.parse(date, DATE_TIME_FORMATTER);
} catch (Exception e) {
throw new InvalidDateFormatException("Invalid format" + date);
}
}
}
这是我的自定义异常类:
public class InvalidDateFormatException extends RuntimeException {
public InvalidDateFormatException(final String message) {
super(message);
}
}
这是我的 ApplicationExceptionHandler 类:
@ControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {
public static final String MISSING_HEADER_MESSAGE = "{0} header must be informed";
@ExceptionHandler(InvalidDateFormatException.class)
public ResponseEntity<String> handleInvalidDateFormatException(InvalidDateFormatException ex) {
// Customize the response based on your needs
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
当我发送出生日期格式错误的申请时,代码进入解串器,捕获异常,但不会引发自定义错误。我刚刚得到一个通用的 400,如下图所示:
我没有更多关于如何解决这个问题的线索。
@RestControllerAdvice
而不是 @ControllerAdvice
。
我相信你的代码实际上确实抛出了
InvalidDateFormatException
,但它并没有像你期望的那样稍后处理。
您问题的标题可能不应该是“Jackson Not Throwing Custom Exception”,而应该是“Rest Controller does not return error as JSON”或类似内容。