SpringMVC异常处理

SpringMVC异常处理分局部异常处理和全局异常处理,首先在局部异常处理中找匹配精准度最高的,若找不到就去找全局异常处理

//局部异常处理(写在当前处理器内)方法上使用@ExceptionHandler注解

@Controller
public class SpringMVCTest {
 
 @ExceptionHandler({RuntimeException.class})
 public ModelAndView handlerRuntimeException(Exception e){
  System.out.println("出异常了:"+e);
  ModelAndView mav=new ModelAndView("error");
  mav.addObject("exception", e);
  return mav;
 }
 
 @ExceptionHandler({ArithmeticException.class})
 public ModelAndView handlerArithmeticException(Exception e){ //精准度更高,优先匹配这个
  System.out.println("-->出异常了:"+e);
  ModelAndView mav=new ModelAndView("error");
  mav.addObject("exception", e);
  return mav;
 }
 
 @RequestMapping("/testExceptionHandlerExceptionResolver")
 public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
  System.out.println("result:" +(10/i)); //i=0时发生ArithmeticException
  return "success";
 }

}

//全局异常处理(专门写一个处理器类)类上使用@ControllerAdvice注解,方法上使用@ExceptionHandler注解

@ControllerAdvice
public class HandlerExceptionHandler {

 @ExceptionHandler({ArithmeticException.class})
 public ModelAndView handlerArithmeticException(Exception e){
  System.out.println("===>出异常了:"+e);
  ModelAndView mav=new ModelAndView("error");
  mav.addObject("exception", e);
  return mav;
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值