Tuesday, 6 August 2013

In Spring MVC, where to catch Database exceptions

In Spring MVC, where to catch Database exceptions


I am following the structure suggested above at (
http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/
). I tried adding a duplicate entry, which resulted in the following
exception:
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/cct] threw exception [Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: Duplicate entry
'a@b.com' for key 'PRIMARY'; SQL [n/a]; constraint [null]; nested
exception is org.hibernate.exception.ConstraintViolationException:
Duplicate entry 'a@b.com' for key 'PRIMARY'] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry 'a@b.com' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at << removed for readability>>
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy26.addUser(Unknown Source)
at
com.bilitutor.cct.control.HomeController.signup(HomeController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
<< removed for readability>>
I have the following questions:
Why is the exception being caught by the Controller (
userService.addUser(user) in com.bilitutor.cct.control.HomeController )
and not by the DAO ( sessionFactory.getCurrentSession().save(user); ) and
then bubbled up to the Controller?
I understand that I am getting a
org.springframework.dao.DataIntegrityViolationException because I am using
the @Repository annotation, which perhaps does exception translation
(correct me if I am wrong). In that case, when I catch the exception, how
do I find the error code for it?
As a best practice, on which layer (DAO, Service or Controller) is the
best spot to catch the exception?

No comments:

Post a Comment