SpringBoot的全局異常處理

1.前言

項目經常會出現各種異常情況,如果所有都使用try-catch語句,無疑代碼重複率相當的高,恰巧Spring給我們解決了這個問題:
@ExceptionHandler配置這個註解可以處理異常, 但是僅限於當前Controller中處理異常。
那麼有沒有什麼辦法可以讓所有controller都處理呢,恰巧也有:
@ControllerAdvice是一個增強的controller,可以配置basePackage下的所有controller. 所以結合兩者使用,就可以處理全局的異常了.

2.代碼

package com.zsl.springboot.bootdemo.utils;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 系統發生500異常的處理方式
     * @param e 指定處理的異常
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public String customException(Exception e) {
        return "error";
    }
}

通過這種配置,我們項目當中出現異常的地方,都會準確的跳到error界面。

上面這種對於500的異常以及可以處理了,那麼對於404的資源又該怎麼處理呢?

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer = factory -> {
            ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND,"/404");
            factory.addErrorPages(errorPage);
        };
        return webServerFactoryCustomizer;
    }

同一個controlleradvice下面增加這個bean即可做到

Github源碼:https://github.com/managerlu/bootdemo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章