位置:首页 > > SpringMVC异常的处理

SpringMVC异常的处理

1.处理局部异常(Controller内)
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);
    System.out.println("in testExceptionHandler");
    return mv;
}
    
@RequestMapping("/error")
public String error(){
    int i = 5/0;
    return "hello";
}
2.处理全局异常(所有Controller)
@ControllerAdvice
public class testControllerAdvice {
    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception ex){
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("exception", ex);
        System.out.println("in testControllerAdvice");
        return mv;
    }
}

3.另一种处理全局异常的方法

在SpringMVC配置文件中配置

<!-- configure SimpleMappingExceptionResolver -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
</bean>


error是出错页面