我有一个PropertyEditor来将id转换为Persons,其setAsText(字符串文本)如下:
public void setAsText(String text) throws IllegalArgumentException {
try {
int id = Integer.parseInt(text);
Person person = peopleService.get(id);
this.setValue(person);
}
catch (NumberFormatException ex) {
// ...
throw new IllegalArgumentException("Not a number!: " + text);
}
catch (PersonNotFoundExcetion ex) {
// ...
throw new IllegalArgumentException("Impossible to get Person: " + text);
}
}
我的 PeopleController 有一个方法如下:
@RequestMapping("/getPerson")
public void ver (@RequestParam Person person, Model model) {
model.addAttribute (person);
// ...
}
我想捕获 IllegalArgumentException 以便向用户显示友好的消息,例如“抱歉,您要找的人不在这里”,但我不知道在哪里执行此操作...
谢谢!
最佳答案
一般的异常处理可以这样完成:
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAllExceptions(Exception e) {
return "redirect:/error.html"; /* use the correct view name */
}
更具体的,您可以使用 BindingResult
@RequestMapping(value = "/datedata", method = RequestMethod.POST)
public String create(
@ModelAttribute("datedata") final DateData datedata,
final BindingResult result) {
if (result.hasErrors()) {
return "datedata/create";
} else {
...
return "myView";
}
}
但我想这只适用于“Forms”(ModelAttribute)
以我的拙见,让 Spring 处理属性编辑器对用户输入的验证并不是一个好主意。我强烈建议使用 Form 方式:构建一个带有 STRING 字段的命令对象并在其上使用 validator 。
关于java - 捕获 Spring 中 PropertyEditors 抛出的 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4793738/