SpringBoot如何實(shí)現(xiàn)統(tǒng)一異常處理

這篇文章將為大家詳細(xì)講解有關(guān)SpringBoot如何實(shí)現(xiàn)統(tǒng)一異常處理,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

游仙網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計(jì)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)公司成立與2013年到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。

1.介紹

在日常開發(fā)中發(fā)生了異常,往往是需要通過一個統(tǒng)一的異常處理處理所有異常,來保證客戶端能夠收到友好的提示。SpringBoot在頁面發(fā)生異常的時候會自動把請求轉(zhuǎn)到/error,SpringBoot內(nèi)置了一個BasicErrorController對異常進(jìn)行統(tǒng)一的處理,當(dāng)然也可以自定義這個路徑

application.yaml

server:
 port: 8080
 error:
 path: /custom/error

BasicErrorController提供兩種返回錯誤一種是頁面返回、當(dāng)你是頁面請求的時候就會返回頁面,另外一種是json請求的時候就會返回json錯誤

 @RequestMapping(produces = "text/html")
 public ModelAndView errorHtml(HttpServletRequest request,
   HttpServletResponse response) {
  HttpStatus status = getStatus(request);
  Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
    request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  response.setStatus(status.value());
  ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  return (modelAndView == null &#63; new ModelAndView("error", model) : modelAndView);
 }

 @RequestMapping
 @ResponseBody
 public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  Map<String, Object> body = getErrorAttributes(request,
    isIncludeStackTrace(request, MediaType.ALL));
  HttpStatus status = getStatus(request);
  return new ResponseEntity<Map<String, Object>>(body, status);
 }

分別會有如下兩種返回

SpringBoot如何實(shí)現(xiàn)統(tǒng)一異常處理

{
 "timestamp": 1478571808052,
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/rpc"
}

2.通用Exception處理

通過使用@ControllerAdvice來進(jìn)行統(tǒng)一異常處理,@ExceptionHandler(value = Exception.class)來指定捕獲的異常

下面針對兩種異常進(jìn)行了特殊處理分別返回頁面和json數(shù)據(jù),使用這種方式有個局限,無法根據(jù)不同的頭部返回不同的數(shù)據(jù)格式,而且無法針對404、403等多種狀態(tài)進(jìn)行處理

 @ControllerAdvice
 public class GlobalExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";
  @ExceptionHandler(value = CustomException.class)
  @ResponseBody
  public ResponseEntity defaultErrorHandler(HttpServletRequest req, CustomException e) throws Exception {
   return ResponseEntity.ok("ok");
  }
  @ExceptionHandler(value = Exception.class)
  public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
   ModelAndView mav = new ModelAndView();
   mav.addObject("exception", e);
   mav.addObject("url", req.getRequestURL());
   mav.setViewName(DEFAULT_ERROR_VIEW);
   return mav;
  }
 }

3.自定義BasicErrorController 錯誤處理

在初始介紹哪里提到了BasicErrorController,這個是SpringBoot的默認(rèn)錯誤處理,也是一種全局處理方式。咱們可以模仿這種處理方式自定義自己的全局錯誤處理

下面定義了一個自己的BasicErrorController,可以根據(jù)自己的需求自定義errorHtml()和error()的返回值。

 @Controller
 @RequestMapping("${server.error.path:${error.path:/error}}")
 public class BasicErrorController extends AbstractErrorController {
  private final ErrorProperties errorProperties;
  private static final Logger LOGGER = LoggerFactory.getLogger(BasicErrorController.class);
  @Autowired
  private ApplicationContext applicationContext;

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties) {
   this(errorAttributes, errorProperties,
     Collections.<ErrorViewResolver>emptyList());
  }

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   * @param errorViewResolvers error view resolvers
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
   super(errorAttributes, errorViewResolvers);
   Assert.notNull(errorProperties, "ErrorProperties must not be null");
   this.errorProperties = errorProperties;
  }

  @Override
  public String getErrorPath() {
   return this.errorProperties.getPath();
  }

  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
          HttpServletResponse response) {
   HttpStatus status = getStatus(request);
   Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
     request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
   response.setStatus(status.value());
   ModelAndView modelAndView = resolveErrorView(request, response, status, model);
   insertError(request);
   return modelAndView == null &#63; new ModelAndView("error", model) : modelAndView;
  }



  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
   Map<String, Object> body = getErrorAttributes(request,
     isIncludeStackTrace(request, MediaType.ALL));
   HttpStatus status = getStatus(request);
   insertError(request);
   return new ResponseEntity(body, status);
  }

  /**
   * Determine if the stacktrace attribute should be included.
   *
   * @param request the source request
   * @param produces the media type produced (or {@code MediaType.ALL})
   * @return if the stacktrace attribute should be included
   */
  protected boolean isIncludeStackTrace(HttpServletRequest request,
            MediaType produces) {
   ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
   if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
    return true;
   }
   if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
    return getTraceParameter(request);
   }
   return false;
  }

  /**
   * Provide access to the error properties.
   *
   * @return the error properties
   */
  protected ErrorProperties getErrorProperties() {
   return this.errorProperties;
  }
 }

SpringBoot提供了一種特殊的Bean定義方式,可以讓我們?nèi)菀椎母采w已經(jīng)定義好的Controller,原生的BasicErrorController是定義在ErrorMvcAutoConfiguration中的

具體代碼如下:

 @Bean
 @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
 public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
  return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
    this.errorViewResolvers);
 }

可以看到這個注解@ConditionalOnMissingBean 意思就是定義這個bean 當(dāng) ErrorController.class 這個沒有定義的時候, 意思就是說只要我們在代碼里面定義了自己的ErrorController.class時,這段代碼就不生效了,具體自定義如下:

 @Configuration
 @ConditionalOnWebApplication
 @ConditionalOnClass({Servlet.class, DispatcherServlet.class})
 @AutoConfigureBefore(WebMvcAutoConfiguration.class)
 @EnableConfigurationProperties(ResourceProperties.class)
 public class ConfigSpringboot {
  @Autowired(required = false)
  private List<ErrorViewResolver> errorViewResolvers;
  private final ServerProperties serverProperties;

  public ConfigSpringboot(
    ServerProperties serverProperties) {
   this.serverProperties = serverProperties;
  }

  @Bean
  public MyBasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
   return new MyBasicErrorController(errorAttributes, this.serverProperties.getError(),
     this.errorViewResolvers);
  }
 }

在使用的時候需要注意MyBasicErrorController不能被自定義掃描Controller掃描到,否則無法啟動。

3.總結(jié)

一般來說自定義BasicErrorController這種方式比較實(shí)用,因?yàn)榭梢酝ㄟ^不同的頭部返回不同的數(shù)據(jù)格式,在配置上稍微復(fù)雜一些,但是從實(shí)用的角度來說比較方便而且可以定義通用組件

關(guān)于SpringBoot如何實(shí)現(xiàn)統(tǒng)一異常處理就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

網(wǎng)站名稱:SpringBoot如何實(shí)現(xiàn)統(tǒng)一異常處理
文章源于:http://muchs.cn/article6/iephog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、小程序開發(fā)、動態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作、域名注冊虛擬主機(jī)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計(jì)