Java SpringBoot数据异常处理
我有一个spring boot post控制器,它有一个日期作为参数,具有特定的格式,问题是如果用户以不同的格式提交表单,应用程序将崩溃,我不确定该如何处理:( 控制器:Java SpringBoot数据异常处理,java,spring,date,spring-boot,Java,Spring,Date,Spring Boot,我有一个spring boot post控制器,它有一个日期作为参数,具有特定的格式,问题是如果用户以不同的格式提交表单,应用程序将崩溃,我不确定该如何处理:( 控制器: @RequestMapping(value = "/findFlights", method = RequestMethod.POST) public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
@RequestMapping(value = "/findFlights", method = RequestMethod.POST)
public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
@RequestParam("departureDate") @DateTimeFormat(pattern = "MM-dd-yyyy") Date departureDate, Model model) {
List<Flight> flights = flightRepository.findFlights(from, to, departureDate);
if(flights.isEmpty()) {
model.addAttribute("msg", "No flights were found!");
}else {
model.addAttribute("flights", flights);
foundFlights = true;
model.addAttribute("foundFlights", foundFlights);
}
return "displayFlights";
}
但是,如果日期是例如:2018年10月15日,它将起作用……处理这个问题的最佳方法是什么?您可以执行以下操作之一:
- 您可以以字符串形式接收日期,在服务中转换日期,并将所需的错误信息返回给客户端
- 实施异常处理程序建议,并将所需答案/错误返回给客户端
- 以json的形式接收数据,并在json上编写自己的格式化程序(字符串到日期),然后如果格式错误,您可以抛出自己的异常
- 您可以以字符串形式接收日期,在服务中转换日期,并将所需的错误信息返回给客户端
- 实施异常处理程序建议,并将所需答案/错误返回给客户端
- 以json的形式接收数据,并在json上编写自己的格式化程序(字符串到日期),然后如果格式错误,您可以抛出自己的异常
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '22-22-2018'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [22-22-2018]