Announcement Announcement Module
Collapse
No announcement yet.
Properly formatting REST response when encountering exception Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Properly formatting REST response when encountering exception

    Hi, I am trying to use @ResponseBody to facilitate marshaling of RESTful services (see code snippet below for example). However, I want to make sure that when an exception is encountered that the response is still in the requested format (JSON, XML, etc.). It appears that the default behavior renders a standard HTML error page.

    Is there a recommended way to accomplish this? Since I haven't been able to find anything I have just written an aspect that catches any unhandled exceptions and returns our RestResponse class (see below). However, that results in a 200 response code which is obviously incorrect.

    I feel like I'm probably headed down the wrong path here so thought I'd better ask to see if anyone has a recommendation about a better way to solve this problem.

    Thanks,
    Scott


    Controller Method:
    Code:
        @RequestMapping(value="{listId}", method = RequestMethod.GET)
        public @ResponseBody RestResponse getDatabase(@PathVariable("listId") Integer listId) {
            return new RestResponse(listOfLists.get(listId));
        }
    Aspect:
    Code:
        @Pointcut("execution(samples.mvc.ajax.account.RestResponse *(..))")
        public void anyRestMethodExecution() {}
    
        @Around("anyRestMethodExecution()")
          public Object handleRestErrors(ProceedingJoinPoint pjp) {
            try {
                return pjp.proceed();
            } catch (Throwable e) {
                return new RestResponse(RestResponse.StatusEnum.ERROR, e.getMessage());
            }
        }

  • #2
    Well that was easy

    Hi everyone, well it turns out this must have been considered a bug in 3.0. I upgraded my sample project to 3.1 and @ExceptionHandler now seems to work properly. So the following exception handler method now returns the appropriate response type.


    Code:
        @ExceptionHandler(TypeMismatchException.class)
        public @ResponseBody RestResponse handleTypeMismatchException(TypeMismatchException e) {
            return new RestResponse(RestResponse.StatusEnum.ERROR, e.getMessage());
        }

    Comment

    Working...
    X