SpringBoot全局异常的捕获设置

Posted ╱、隐风っ九剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot全局异常的捕获设置相关的知识,希望对你有一定的参考价值。

1、新建立一个捕获异常的实体类

如:LeeExceptionHandler

 1 package com.leecx.exception;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.springframework.web.bind.annotation.ControllerAdvice;
 7 import org.springframework.web.bind.annotation.ExceptionHandler;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 @ControllerAdvice
11 public class LeeExceptionHandler {
12     
13     public static final String DEFAULT_ERROR_VIEW = "error";
14     
15 
16     
17     @ExceptionHandler(value = Exception.class)
18     public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception {
19         
20         e.printStackTrace();
21         
22         if (isAjax(reqest)) {
23             return response;
24         } else {
25             ModelAndView mav = new ModelAndView();
26             mav.addObject("exception", e);
27             mav.addObject("url", reqest.getRequestURL());
28             mav.setViewName(DEFAULT_ERROR_VIEW);
29             return mav;
30         }
31     }
32     
33     
34     public static boolean isAjax(HttpServletRequest httpRequest){
35         return  (httpRequest.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( httpRequest.getHeader("X-Requested-With").toString()) ) ;
36     }
37 
38     
39 }

在类上面加入注解:@ControllerAdvice

在处理方法上面加入注解@ExceptionHandler(value = Exception.class)

然后设置相应的业务处理。跳转到 特需的处理错误的友好业务界面。

以上是关于SpringBoot全局异常的捕获设置的主要内容,如果未能解决你的问题,请参考以下文章

springboot中添加全局异常捕获类

springboot中有了全局异常捕获,还需要try catch吗?

springboot捕获全局异常和配置多数据源

SpringBoot配置全局异常捕获

springboot全局捕获异常

spring-- springboot配置全局异常处理器