java - 捕获 Spring 中 PropertyEditors 抛出的 IllegalArgumentException

标签 java spring spring-mvc

我有一个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/

相关文章:

java - 如何使 JFrame 成为一种颜色?

java - KSQL 数据生成 - java.lang.ClassNotFoundException : MonitoringProducerInterceptor

java - Java、Spring 和 Angularjs Web 应用程序的最佳方法是什么?

java - 使用 spring 的 pom.xml 中的 Maven 错误

java - Spring Boot RabbitMQ 接收器 Jackson 反序列化为 POJO

jquery - Spring MVC 未找到匹配的编辑器或转换策略

java - 重构java方法以降低圈复杂度

java - 标准 API IN 与 ArrayList

java - 将照片上传到 OpenShift。 Spring MVC

java - 如何设置背景颜色 TabHost