十四、异常的处理
十四、异常的处理
https://www.cnblogs.com/sunniest/p/4555801.html
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是出错页面
package test.SpringMVC; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/exception") public class exceptionController { //http://localhost:8080/HiSpringMVC/exception/hello @RequestMapping("/hello") public String hello(){ return "hello"; } @ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testExceptionHandler"); return mv; } //http://localhost:8080/HiSpringMVC/exception/error @RequestMapping("/error") public String error(){ int i = 5/0; return "hello"; } }

 

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号