Wednesday, June 22, 2011

Exception Handling in Spring MVC

Here is one good and easy way to do it
First of all We should create a user defined exception class

public class MyExceptionClass extends RuntimeException {
private String userMessage = "User message not set";

public MyExceptionClass() {
super();
}

public MyExceptionClass(String userMessage, Throwable cause) {
super(cause);
this.userMessage = userMessage;
}

public MyExceptionClass(String userMessage) {
super(userMessage);
this.userMessage = userMessage;
}

public MyExceptionClass(Throwable cause) {
super(cause);
userMessage = cause.getMessage();
}

public String getUserMessage() {
return userMessage;
}

public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}

@Override
public String toString() {
return "User message = " + userMessage + "\n" + super.toString();
}
}

Next step is to configure exception handling in application context file

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="MyExceptionClass">error</prop>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
</bean>

No comments: