繁体   English   中英

SpringBoot数据异常处理

[英]SpringBoot Data exception handling

我有一个spring boot post控制器,该控制器的日期带有特定格式的参数,问题是,如果用户使用其他格式提交表单,应用程序将崩溃,我不确定如何处理此问题: (控制器:

@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";
    }

基本上,如果提交的日期是这样的:22-22-2018它会给我这个例外:

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上编写自己的格式化程序(字符串为date),然后,如果格式错误,则可以引发自己的异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM