一、基于注解
package com.test.restful.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class Exception {
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
public String exception(Exception exception, Model model) {
model.addAttribute("exception", exception);
return "error";
}
}
二、基于配置–SpringMVC.xml
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<property name="exceptionAttribute" value="exception"></property>
</bean>