【发布时间】:2019-07-29 09:55:35
【问题描述】:
在我的应用程序中,我将fromCurrency、toCurrency 和amount 这三个参数的值输入到地址栏中
并在控制器中。我想检查输入数据的正确性。但是我在测试期间产生了一个异常,没有进一步
那些。我需要一个代码,控制器中的代码将检查输入数据的正确性,并且根据发生错误的字段,将产生第 400 个错误,其名称为错误填写的字段
我试过这个验证,用
if(!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency)))
但如果 Currency 不包含 fromCurrency 则会生成异常
@RestController
class ExchangeController {
private static final Logger logger = Logger.getLogger(ExchangeController.class.getName());
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
@Qualifier("dataService")
private CurrencyExchangeService currencyExchangeService;
@SuppressWarnings("SameReturnValue")
@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
public String start() {
return "input parameters";
}
@RequestMapping(value = "/convert", method = RequestMethod.GET, produces = "application/json")
public ExchangeRateDTO converting(@RequestParam("fromCurrency") String fromCurrency,
@RequestParam("toCurrency") String toCurrency,
@RequestParam("amount") String amount) throws IOException {
if (!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency))) {
}
BigDecimal convertedAmount = currencyExchangeService.convert(fromCurrency, toCurrency, new BigDecimal(amount));
return new ExchangeRateDTO(fromCurrency, toCurrency, new BigDecimal(amount), convertedAmount);
}
}
【问题讨论】:
-
将您的
fromCurrency和toCurrency从String更改为Currency和amount更改为BigDecimal。如果 Spring 不能转换,Spring 将进行转换或异常。如果您真的想坚持使用String(我建议不要这样做),请使用表单对象并编写Validator来进行验证。
标签: java spring-boot exception currency