@ExceptionHandler(Exception.class)和@ControllerAdvice

第一种,直接在Controller层写@ExceptionHandler注解,对于指定异常,可以处理并返回一个视图或者body:

@Controller
public class HelloWorld {

    @RequestMapping("test")
    public String test(int flag) throws FileNotFoundException {
        if (1 == flag) {
            throw new FileNotFoundException("文件找不到");
        }
        if (2 == flag) {
            int i = 1 / 0;
        }
        return "hello";
    }

    @ExceptionHandler(IOException.class)
    public ModelAndView h(Exception e, HttpServletRequest req, HttpServletResponse resp, HttpSession sesseion) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("name", e.getMessage());
        return modelAndView;
    }

    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public String h1(Exception e, HttpServletRequest req, HttpServletResponse resp, HttpSession sesseion) {
        return req.getRequestURI() + "抛出异常" + e.getClass().getName() + e.getMessage();
    }

}

第二种,全局异常处理,通过@ControllerAdvice对所有Controller进行切面通知,可以指定父类
@ExceptionHandler可以指定父类异常

@ControllerAdvice(assignableTypes = HelloWorld.class)
public class ExceptionHanlderClass {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String handleExceptions(Exception e, HttpServletRequest req){
        return req.getRequestURI() + "抛出一个异常" + e.getClass().getName() + e.getMessage();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值