如何以编程方式将Spring的NumberFormatException替换为用户友好的文本?
2022-09-03 15:59:57
我正在开发一个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";
}
验证方法只是检查数据库中是否已经存在该名称,因此我没有将其包括在内。我的问题是,当我故意在字段中输入文本时,我希望有一个不错的消息,例如“自动放电时间必须是一个数字!相反,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"
我完全理解为什么会发生这种情况,但我无法弄清楚如何以编程方式将Spring的默认数字格式异常错误消息替换为我自己的错误消息。我知道消息源可用于此类事情,但我真的想直接在代码中实现这一点。
编辑
正如建议的那样,我在控制器中构建了这种方法,但我仍然得到Spring的“未能转换属性值...”消息:
@ExceptionHandler({NumberFormatException.class})
private String numberError()
{
return "The auto-discharge time must be a number!";
}
其他编辑
以下是我的实体类的代码:
@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() + ")";
}
}
又一次编辑
我能够使用类路径上的 message.properties 文件来完成这项工作,其中包含以下内容:
typeMismatch.java.lang.Integer={0} must be a number!
以及配置文件中的以下 Bean 声明:
@Bean
public ResourceBundleMessageSource messageSource()
{
ResourceBundleMessageSource resource = new ResourceBundleMessageSource();
resource.setBasename("message");
return resource;
}
这给了我正确的错误消息,而不是Spring通用TypeMismatchException / NumberFormatException,我可以忍受,但仍然想尽可能地以编程方式完成所有事情,我正在寻找替代方案。
感谢您的帮助!