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"
        <property name="messageConverters">
                <ref bean="jacksonMessageConverter" />

    <bean id="jacksonMessageConverter"

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

Step 3: In controller class :

    @RequestMapping(value="/test", method = RequestMethod.GET)
    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 })
    public ErrorResponse handleException(Exception ex,
            HttpServletRequest request, HttpServletResponse response) {
        ErrorResponse errorResponse = new ErrorResponse();
        return errorResponse;


{"message": "your_message"}

Feel free to comment :)


  1. thanx , i worked prefectly fine for me.

  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.


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...