简体   繁体   中英

How to Catch/Handle Type Binding Errors in Spring MVC

Suppose my form fields map to an Integer, Short, etc., and the input is invalid (non-numeric).

I get the following in my errors map upon form submission:

Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Short' for property 'property'; nested exception is java.lang.NumberFormatException: For input string: "a" 

I need to show a custom, user-friendly message. This doesn't work for me, it never comes here:

@ExceptionHandler(NumberFormatException.class)
public String handleNumberConversion(NumberFormatException nfe)
{
    return "error.invalidNumberFormat";
}  

BindException doesn't work either - in fact even a generic Exception in the method signature won't get activated.

EDIT: 2nd Attempt: I even tried this, this doesn't work either in my Resource Bundle, either:

# SpringMVC Error Overrides
typeMismatch.java.lang.NumberFormatException=A NumberFormatException occurred.
typeMismatch.java.lang.Short={0} is an invalid value.
typeMismatch.java.lang.Integer={0} is an invalid value.

Also , I need to get some details from the Binding process exception, such as the field that was being bound and the current value, because my custom error message shows this information.

Your handler method needs a different signature:

@ExceptionHandler(BindException.class)
public String handleBindException(BindException be) {
    // extract data from exception...
    return "whatever";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM