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 :)
thanx , i worked prefectly fine for me.
ReplyDeleteTechnoSoftwar 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