Announcement Announcement Module
No announcement yet.
Type Conversion Error Handling for Scalar Handler Method Arguments Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Type Conversion Error Handling for Scalar Handler Method Arguments

    When using Spring MVC what's the recommended approach for performing type conversion of path variables or request parameters to typesafe, scalar Handler method arguments whilst still being able to report the name of the input (path variable or request parameter) in error when the type conversion fails?

    We're building some RESTful APIs and we need to be able to identify the names of erroneous client inputs, including path variables (e.g. resource ID "foo1" in URL /foo/{fooId}/bar) and request params. At the same time we'd still also like to benefit from automatic type conversion in our Handlers, e.g. resource ID path variables to Integer, or date/time request parameters to Date, e.g.
      @RequestMapping(value = "/foo/{fooId}/bar", method = RequestMethod.GET, produces = "application/xml")
      public BarsResource getBars(
        @PathVariable Integer fooId,
        @RequestParam(value = "since", required = false) final Date since, ....)  {...}
    When using standard data binding support for Handler args that are composite objects the BindingResult can be used to identify the argument in error when type conversion fails. However, for scalar variables, such as in the example above, a type conversion failure typically results in a TypeMismatchException which has no context info, only identifying the invalid value and target type.

    Using a custom Converter offers a potential solution as the API includes a TypeDescriptor which can identify the method param (either by name or annotation data), and if conversion fails the default ConversionService include the TypeDescriptor when wrapping an rethrowing the type conversion exception. But this doesn't work when there is a default property editor for the same convertible pair (e.g. String to Integer). In Spring 3.1, ConversionFailedException are trapped and saved by TypeConverterDelegate.convertIfNecessary(), the default PropertyEditor is invoked, and if it fails the PropertyEditor's resulting exception is thrown, bereft of any contextual info, instead of rethrowing the saved original ConversionException. This exception handling logic seems questionable to me. (This post reports the same issue).

    As things stand we're thinking of foregoing automatic type conversion, reverting back to using Strings for Controller method arguments and invoking the conversion logic from within the Controllers, where we can throw exceptions identifying the name of erroneous input.

    I assume this is a common requirement. What's best practice / the recommended approach?

    Thanks in advance,
    Last edited by Neil Brown; Sep 8th, 2012, 04:01 AM.