2.处理全局异常(所有Controller)

十四、异常的处理

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;
    }
}
复制代码
 
package test.SpringMVC;
//D:\Indigo_workspace2\HelloSpringMVC\src\test\SpringMVC\JimController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/jim")
public class JimController {

    int counter=0;
    
    //http://localhost:8080/HiSpringMVC/jim/hello
    @RequestMapping("/hello")
    public String hello(){  
        int i = 5/0;
        return "hello";
    }
package test.SpringMVC;
//D:\Indigo_workspace2\HiSpringMVC\src\test\SpringMVC\testControllerAdvice.java
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;


@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是出错页面

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

 

posted @ 2018-01-11 19:23  sky20080101  阅读(178)  评论(0)    收藏  举报