如何以编程方式用用户友好的文本替换Spring的NumberFormatException?

Mar*_*tin 14 java spring message replace numberformatexception

我正在开发一个Spring Web应用程序,我有一个具有Integer属性的实体,用户可以在使用JSP表单创建新实体时填写该属性.此表单调用的控制器方法如下:

@RequestMapping(value = {"/newNursingUnit"}, method = RequestMethod.POST)
public String saveNursingUnit(@Valid NursingUnit nursingUnit, BindingResult result, ModelMap model) 
{
    boolean hasCustomErrors = validate(result, nursingUnit);
    if ((hasCustomErrors) || (result.hasErrors()))
    {
        List<Facility> facilities = facilityService.findAll();
        model.addAttribute("facilities", facilities);

        setPermissions(model);

        return "nursingUnitDataAccess";
    }

    nursingUnitService.save(nursingUnit);
    session.setAttribute("successMessage", "Successfully added nursing unit \"" + nursingUnit.getName() + "\"!");
    return "redirect:/nursingUnits/list";
}
Run Code Online (Sandbox Code Playgroud)

validate方法只检查DB中是否已存在名称,因此我没有包含它.我的问题是,当我故意在现场输入文字时,我希望有一个很好的信息,例如"自动放电时间必须是一个数字!".相反,Spring返回了这个绝对可怕的错误:

Failed to convert property value of type [java.lang.String] to required type [java.lang.Integer] for property autoDCTime; nested exception is java.lang.NumberFormatException: For input string: "sdf"
Run Code Online (Sandbox Code Playgroud)

我完全理解为什么会发生这种情况,但我不能为我的生活弄清楚如何以编程方式用我自己的替换Spring的默认数字格式异常错误消息.我知道可以用于此类事情的消息源,但我真的想直接在代码中实现这一点.

编辑

正如所建议的,我在我的控制器中构建了这个方法,但我仍然得到Spring的"未能转换属性值..."消息:

@ExceptionHandler({NumberFormatException.class})
private String numberError()
{
   return "The auto-discharge time must be a number!";
}
Run Code Online (Sandbox Code Playgroud)

其他编辑

这是我的实体类的代码:

@Entity
@Table(name="tblNursingUnit")
public class NursingUnit implements Serializable 
{
private Integer id;
private String name;
private Integer autoDCTime;
private Facility facility;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() 
{
    return id;
}

public void setId(Integer id) 
{
    this.id = id;
}

@Size(min = 1, max = 15, message = "Name must be between 1 and 15 characters long")
@Column(nullable = false, unique = true, length = 15)
public String getName() 
{
    return name;
}

public void setName(String name) 
{
    this.name = name;
}

@NotNull(message = "The auto-discharge time is required!")
@Column(nullable = false)
public Integer getAutoDCTime() 
{
    return autoDCTime;
}

public void setAutoDCTime(Integer autoDCTime) 
{
    this.autoDCTime = autoDCTime;
}

@ManyToOne (fetch=FetchType.EAGER)
@NotNull(message = "The facility is required")
@JoinColumn(name = "id_facility", nullable = false)
public Facility getFacility()
{
    return facility;
}

public void setFacility(Facility facility)
{
    this.facility = facility;
}

@Override
public boolean equals(Object obj) 
{
    if (obj instanceof NursingUnit)
    {
        NursingUnit nursingUnit = (NursingUnit)obj;
        if (Objects.equals(id, nursingUnit.getId()))
        {
            return true;
        }
    }
    return false;
}

@Override
public int hashCode() 
{
    int hash = 3;
    hash = 29 * hash + Objects.hashCode(this.id);
    hash = 29 * hash + Objects.hashCode(this.name);
    hash = 29 * hash + Objects.hashCode(this.autoDCTime);
    hash = 29 * hash + Objects.hashCode(this.facility);
    return hash;
}

@Override
public String toString()
{
    return name + " (" + facility.getCode() + ")";
}
}
Run Code Online (Sandbox Code Playgroud)

再来一次编辑

我能够使用包含以下内容的类路径上的message.properties文件来完成这项工作:

typeMismatch.java.lang.Integer={0} must be a number!
Run Code Online (Sandbox Code Playgroud)

以及配置文件中的以下bean声明:

@Bean
public ResourceBundleMessageSource messageSource() 
{
    ResourceBundleMessageSource resource = new ResourceBundleMessageSource();
    resource.setBasename("message");
    return resource;
}
Run Code Online (Sandbox Code Playgroud)

这给了我正确的错误消息,而不是我可以忍受的Spring泛型TypeMismatchException/NumberFormatException但是,我仍然希望尽可能以编程方式执行所有操作,并且我正在寻找替代方案.

谢谢您的帮助!

Sun*_*amy -2

处理NumberFormatException。

try {
 boolean hasCustomErrors = validate(result, nursingUnit);
}catch (NumberFormatException nEx){
 // do whatever you want
 // for example : throw custom Exception with the custom message.
}
Run Code Online (Sandbox Code Playgroud)

  • 太糟糕了,你的回答表明你对我所问的问题完全缺乏理解,你本来是可信的。我的验证方法不会抛出 NumberFormatException,它除了在名称字段已存在于数据库中的模型中添加 FieldError 之外什么也不做。 (3认同)