如何使用 Spring Boot 实现异常处理?

本文详细介绍了在SpringBoot中如何使用@ExceptionHandler、@ControllerAdvice、SimpleMappingExceptionResolver及实现HandlerExceptionResolver接口等四种方式来处理异常,每种方式都有其适用场景和优缺点。

如何使用 Spring Boot 实现异常处理?

  • 使用 @ExceptionHandler 注解处理局部异常(只能处理当前controller中的ArithmeticException和NullPointerException异常,缺点就是只能处理单个controller的异常)

    @Controller
    public class ExceptionHandlerController {
    	
    	@RequestMapping("/excep")
    	public String exceptionMethod(Model model) throws Exception {
    		String a=null;
    		System.out.println(a.charAt(1));
    		int num = 1/0;
    		model.addAttribute("message", "没有抛出异常");
    		return "index";
    	}
    
    	@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
    	public String arithmeticExceptionHandle(Model model, Exception e) {
    		model.addAttribute("message", "@ExceptionHandler" + e.getMessage());
    		return "index";
    	}
    }
    
  • 使用 @ControllerAdvice + @ExceptionHandler 注解处理全局异常(value后面可以填写数组)

    @ControllerAdvice
    public class ControllerAdviceException {
    	
    	@ExceptionHandler(value = {NullPointerException.class})
    	public String NullPointerExceptionHandler(Model model, Exception e) {
    		model.addAttribute("message", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage());
    		return "index";
    	}
    }
    
  • 配置 SimpleMappingExceptionResolver 类处理异常(配置类)

    @Configuration
    public class SimpleMappingException {
    	@Bean
    	public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
    
    		SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
    		Properties mappings = new Properties();
    		//第一个参数为异常全限定名,第二个为跳转视图名称
    		mappings.put("java.lang.NullPointerException", "index");
    		mappings.put("java.lang.ArithmeticException", "index");
    		//设置异常与视图映射信息的
    		resolver.setExceptionMappings(mappings);
    		return resolver;
    	}
    }
    
  • 实现 HandlerExceptionResolver 接口处理异常

    @Configuration
    public class HandlerException implements HandlerExceptionResolver {
    	@Override
    	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    
    		ModelAndView modelAndView = new ModelAndView();
    		modelAndView.addObject("message", "实现HandlerExceptionResolver接口");
    
    		//判断不同异常类型,做不同视图跳转
    		if(ex instanceof NullPointerException){
    			modelAndView.setViewName("index");
    		}
    		if(ex instanceof ArithmeticException){
    			modelAndView.setViewName("index");
    		}
    		return modelAndView;
    	}
    }
    

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值