Monday, February 18, 2013

Spring MVC ExceptionHandler gets easier.


Spring MVC exception handling gets easier with @ControllerAdvice with the release of Spring 3.2.1.

You can annotate your class as shown below and add a method to handle exception


@ControllerAdvice
public class AppCoreController
{
@ExceptionHandler(Exception.class)
public @ResponseBody RequestStatus handleException(Exception exception)
{
RequestStatus errorStatus = new RequestStatus();
errorStatus.setMessageCode(-999);
errorStatus.setMessageDescription(exception.getMessage());
return errorStatus;
}
}


Please note that RequestStatus is a custom controller and yeap we are returning an class / object type as oppose to just String data type. 

These add exception handling capabilities to all your existing controller.