zoukankan      html  css  js  c++  java
  • Spring Boot异常处理的五种方式

    Spring Boot异常处理的五种方式

    Spring Boot框架异常处理有五种处理方式,从范围来说包括有全局异常捕获处理方式和局部异常捕获处理方式

    @Controller
    public class ExceptionController {
    	
    	private static final Logger log = LoggerFactory.getLogger(ExceptionController.class);
    	
    	@RequestMapping("/exceptionMethod")
    	public String exceptionMethod(Model model) throws Exception {
    		
    		model.addAttribute("msg", "没有抛出异常");
            
    		int num = 1/0;   //a处
    		log.info(String.valueOf(num));
    		
    		return "home";
    	}
    
    }
    

    上述代码将会在 a处抛出 ArithmeticException 异常。

    一、自定义异常错误页面

    ​ Spring Boot默认的异常处理机制:一旦程序中出现了异常 Spring Boot 就会请求 /error 的 url 。在 Spring Boot 中提供了一个叫 BasicExceptionController 来处理 /error 请求,然后跳转到默认显示异常的页面来展示异常信息。接下来就是自定义异常错误页面了,方法很简单,就是在目录 src/main/resources/templates/ 下定义一个叫 error 的文件,可以是 Jsp 也可以是 html 。

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>自定义 springboot 异常处理页面</title>
    </head>
    <body>
    Springboot BasicExceptionController  错误页面
    <br>
    <span th:text="${msg}"></span>
    </body>
    </html>
    

    二、使用 @ExceptionHandler 注解处理局部异常

    ​ 只能处理使用@ExceptionHandler注解的方法的Controller的异常。

    @Controller
    public class ExceptionController {
    	
    	private static final Logger log = LoggerFactory.getLogger(ExceptionController.class);
    	
    	@RequestMapping("/exceptionMethod")
    	public String exceptionMethod(Model model) throws Exception {
    		
    		model.addAttribute("msg", "没有抛出异常");
    		
    		int num = 1/0;
    		log.info(String.valueOf(num));
    		
    		return "home";
    	}
    	
    	/**
    	 * 描述:捕获 ExceptionController 中的 ArithmeticException 异常
    	 * @param model 将Model对象注入到方法中
    	 * @param e 将产生异常对象注入到方法中
    	 * @return 指定错误页面
    	 */
    	@ExceptionHandler(value = {ArithmeticException.class})
    	public String arithmeticExceptionHandle(Model model, Exception e) {
    		
    		model.addAttribute("msg", "@ExceptionHandler" + e.getMessage());
    		log.info(e.getMessage());
    		
    		return "error";
    	}
    }
    

    注:注解 @ExceptionHandlervalue 的值为数组,表示指定捕获的异常类型

    三、使用 @ControllerAdvice + @ExceptionHandler 注解处理全局异常

    ​ 使用 @ControllerAdvice + @ExceptionHandler 注解能够处理全局异常,这种方式推荐使用,可以根据不同的异常对不同的异常进行处理。

    ​ 使用方式:定义一个类,使用 @ControllerAdvice 注解该类,使用 @ExceptionHandler 注解方法,这里我定义了一个 GlobalException 类表示来处理全局异常,代码如下:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    @ControllerAdvice
    public class GlobalException {
    	
    	private static final Logger log = LoggerFactory.getLogger(GlobalException.class);
    
    	
    	/**
    	 * 描述:捕获 ArithmeticException 异常
    	 * @param model 将Model对象注入到方法中
    	 * @param e 将产生异常对象注入到方法中
    	 * @return 指定错误页面
    	 */
    	@ExceptionHandler(value = {ArithmeticException.class})
    	public String arithmeticExceptionHandle(Model model, Exception e) {
    		
    		model.addAttribute("msg", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage());
    		log.info(e.getMessage());
    		
    		return "error";
    	}
    	
    }
    

    ​ 注:如果需要处理其他异常,例如 NullPointerException 异常,则只需要在 GlobalException 类中定义一个方法使用 @ExceptionHandler(value = {NullPointerException.class}) 注解该方法,在该方法内部处理异常就可以了。

    四、配置 SimpleMappingExceptionResolver 类处理异常

    ​ 通过配置 SimpleMappingExceptionResolver 类处理异常也是全局范围的,通过将 SimpleMappingExceptionResolver 类注入到 Spring 容器。

    import java.util.Properties;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
    
    @Configuration
    public class GlobalException {
    	
    	@Bean
    	public SimpleMappingExceptionResolver
    		getSimpleMappingExceptionResolver(){
    		SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
    		
    		Properties mappings = new Properties();
    		/*
    		 * 参数一:异常的类型,注意必须是异常类型的全名
    		 * 参数二:视图名称
    		 */
    		mappings.put("java.lang.ArithmeticException", "errors");
    		
    		//设置异常与视图映射信息的
    		resolver.setExceptionMappings(mappings);
    		
    		return resolver;
    	}
    }
    

    注:在类上加上 @Configuration 注解,在方法上加上 @Bean 注解,方法返回值必须是 SimpleMappingExceptionResolver

    五、实现 HandlerExceptionResolver 接口处理异常

    通过实现 HandlerExceptionResolver 接口处理异常,第一步是编写类实现 HandlerExceptionResolver 接口。

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    @Configuration
    public class HandlerExceptionResolverImpl implements HandlerExceptionResolver {
    
    	@Override
    	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
    			Exception ex) {
    		ModelAndView modelAndView = new ModelAndView();
    		
    		modelAndView.addObject("msg", "实现 HandlerExceptionResolver 接口处理异常");
    		
    		//判断不同异常类型,做不同视图跳转
    		if(ex instanceof ArithmeticException){
    			modelAndView.setViewName("error");
    		}
    		
    		return modelAndView;
    	}
    
    }
    
    我等的船还不来
  • 相关阅读:
    PAT A1094 The Largest Generation (25 分)——树的bfs遍历
    PAT A1055 The World's Richest (25 分)——排序
    PAT A1052 Linked List Sorting (25 分)——链表,排序
    PAT A1076 Forwards on Weibo (30 分)——图的bfs
    辅导员
    辅导员面试
    C程序设计
    Excel VBA 基本概念
    Excel函数
    导入excel表的数据到数据库ssh
  • 原文地址:https://www.cnblogs.com/lxs1204/p/14274263.html
Copyright © 2011-2022 走看看