Announcement Announcement Module
Collapse
No announcement yet.
ConversionService Converter to return 404 when item not found Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • ConversionService Converter to return 404 when item not found

    Hi all,

    I have had this with 2 rest style API's that I to use the semantics of say ...

    http://HOST/app/pet/{id} to get a pet by id.

    So cool, thats fine can be implemented easily in a controller... now if the id doesn't exist, I want to return a 404 ... it wasn't found.

    If I do that with this code ...

    Code:
        @RequestMapping("pet/{id}")
        @ResponseBody
        public String get(@PathVariable String id) {
           // Lookup by id
           // if not found throw NotFoundException()
        }
    Where the NotFoundException can have a ResponseStatus annotation to return a 404

    ... but If I want to do this ...

    Code:
        @RequestMapping("pet/{id}")
        @ResponseBody
        public String get(@PathVariable Pet id) {
        }
    I need a converter, and if I throw an exception out of the converter, it doesn't get same handling as if it was thrown from the controller. It seems to be wrapped with a couple of other exceptions (ConversionFailedException and TypeMismatchException) before making it to the exception handlers.

    So I've made my own exception resolver ....
    Code:
    public class ExceptionResolver extends AbstractHandlerExceptionResolver implements Ordered {
    
        @Override
        protected ModelAndView doResolveException(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) {
            if(ex instanceof TypeMismatchException && ex.getCause() instanceof ConversionFailedException && ex.getCause().getCause() instanceof MyCustomExcpetion) { // MyCustomException was thrown from the Converter
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return new ModelAndView();
            }
    
            return null;
        }
    ... and this works fine, but seems a bit obtuse ...

    Sample project proving the point (slightly different from the example above)
    https://github.com/smozely/Example-S...erterException / Attachment

    Just trying to find out if there was a better way to do this? or perhaps this info is useful for someone else.
    Cheers,
    Steve
    Attached Files
Working...
X