Wednesday, January 2, 2013

How ExceptionHandler return JSON in spring MVC

I am working on one project where client/server response is in JSON format. It is easy to send object in JSON format but what if some exception occured and you want to send the Exception also in JSON format ?
After n number of trial. I finally able to do the above task

Step 1 : Add following annotation "AnnotationMethodHandlerExceptionResolver" in your <CONTROLLER>-servlet.xml file.


<!-- JSON format support for Exception -->
    <bean id="methodHandlerExceptionResolver"
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>


Step 2: Make sure you have added jackson jars into your classpath.


Step 3: In controller class :



    @RequestMapping(value="/test", method = RequestMethod.GET)
    @ResponseBody
    public String toTest() throws MxlServiceException {

   try {
      int i = 10/0; // it will throw exception which will be caught by handleException(...)
  }catch (Exception e) {
    throw e;
   }
             return "hello";
 }


then catch them both by writing an exception handler that looks like this:

@ExceptionHandler({ Exception.class })
  @ResponseBody
    public ErrorResponse handleException(Exception ex,
            HttpServletRequest request, HttpServletResponse response) {
             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        return errorResponse;
    }


Output:

{"message": "your_message"}


Feel free to comment :)



2 comments:

  1. thanx , i worked prefectly fine for me.

    ReplyDelete
  2. TechnoSoftwar proficient in web design and development, Mobile Apps development, Customized ERPs, CRMs, Web & Mobile Applications, eCommerce platforms etc. TechnoSoftwar deliver best Quality IT solutions on time. TechnoSoftwarhaving qualified and experienced IT professionals that works for your all business demands.

    ReplyDelete

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...