Results 1 to 2 of 2

Thread: Properly formatting REST response when encountering exception

  1. #1
    Join Date
    Feb 2008
    Posts
    7

    Default 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. #2
    Join Date
    Feb 2008
    Posts
    7

    Default 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());
        }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •