gpt4 book ai didi

java - Spring Boot 数据异常处理

转载 作者:行者123 更新时间:2023-12-02 01:50:34 25 4
gpt4 key购买 nike

我有一个 spring boot post Controller ,它有一个日期作为特定格式的参数,问题是,如果用户使用不同的格式提交表单,应用程序会崩溃,我不太确定应该如何处理有了这个:( Controller :

@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 年 22 月 22 日,它会给我这个异常(exception):

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]

但是,如果日期是例如:2018 年 10 月 15 日,它将起作用...处理此问题的最佳方法是什么?

最佳答案

您可以执行以下操作之一:

  • 您可以接收字符串形式的日期,在您的服务中将其转换并向客户端返回所需的错误信息
  • 实现异常处理程序建议并向客户端返回所需的答案/错误
  • 以 json 形式接收数据,并在 json 上编写您自己的格式化程序(日期字符串),然后如果格式错误,您可以抛出自己的异常

关于java - Spring Boot 数据异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com