使用 Spring 中的 ISO 日期作为路径变量时出现自定义错误?
Custom error when using ISO Dates in Spring as path variables?
场景:
我能够为我的端点提供日期,并且我能够使用@DateTimeFormat 注释来确保它们的格式正确。但是,如果它们不是,我不想只返回 400 错误,而是想建立我的响应,也包含一条错误消息。
当前端点:
@GetMapping("/startDate/{startDate}/endDate/{endDate}")
public ResponseEntity<?> performSearchByDateAction(
@PathVariable @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date startDate,
@PathVariable @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date endDate) throws ParseException {
System.out.println(lastChangedStart);
System.out.println(lastChangedEnd);
return ResponseEntity.ok().build();
}
请忽略这个端点所做的只是输出一些日期,然后以 "Ok" 状态响应。我这里的问题是,如果我用格式不正确的日期访问端点,我只会得到 400 错误的请求响应,因为注释会处理它——但实际上我想在响应实体中构建我的 400 响应,以便我可以提供一个关于日期的消息。
@GetMapping("/startDate/{startDate}/endDate/{endDate}")
public ResponseEntity<?> performSearchByDateAction(
@PathVariable String startDateAsString,
@PathVariable String endDateAsString) throws ParseException {
DateTime lastChangedStart = null;
try {
lastCangedStart = DateTimeFormatter.parse(startDateAsString);
} catch (java.time.format.DateTimeParseException e) {
try { // second format
} catch (java.time.format.DateTimeParseException e) {
try { // third format
} catch (java.time.format.DateTimeParseException e) {
}
} catch (java.time.format.DateTimeParseException e) {
System.out.println(lastChangedStart);
System.out.println(lastChangedEnd);
return ResponseEntity.ok().build();
}
可能有更简单的方法,但这对我有用。
场景:
我能够为我的端点提供日期,并且我能够使用@DateTimeFormat 注释来确保它们的格式正确。但是,如果它们不是,我不想只返回 400 错误,而是想建立我的响应,也包含一条错误消息。
当前端点:
@GetMapping("/startDate/{startDate}/endDate/{endDate}")
public ResponseEntity<?> performSearchByDateAction(
@PathVariable @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date startDate,
@PathVariable @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date endDate) throws ParseException {
System.out.println(lastChangedStart);
System.out.println(lastChangedEnd);
return ResponseEntity.ok().build();
}
请忽略这个端点所做的只是输出一些日期,然后以 "Ok" 状态响应。我这里的问题是,如果我用格式不正确的日期访问端点,我只会得到 400 错误的请求响应,因为注释会处理它——但实际上我想在响应实体中构建我的 400 响应,以便我可以提供一个关于日期的消息。
@GetMapping("/startDate/{startDate}/endDate/{endDate}")
public ResponseEntity<?> performSearchByDateAction(
@PathVariable String startDateAsString,
@PathVariable String endDateAsString) throws ParseException {
DateTime lastChangedStart = null;
try {
lastCangedStart = DateTimeFormatter.parse(startDateAsString);
} catch (java.time.format.DateTimeParseException e) {
try { // second format
} catch (java.time.format.DateTimeParseException e) {
try { // third format
} catch (java.time.format.DateTimeParseException e) {
}
} catch (java.time.format.DateTimeParseException e) {
System.out.println(lastChangedStart);
System.out.println(lastChangedEnd);
return ResponseEntity.ok().build();
}
可能有更简单的方法,但这对我有用。