1. 程式人生 > >SpringBoot 進階系列一 定義全域性異常@

SpringBoot 進階系列一 定義全域性異常@ 阿新 發佈:2018-11-21

此方式優點是不用再control層進行try catch了

此方式的缺點恰恰也是隻能反饋control層的相關異常

首先我們定義一下,建立全域性異常控制類,並在類頭上添加註解:@controllerAdvice

@ControllerAdvice
public class GlobalExceptionHandler {
}

在方法中寫入自定義異常丟擲方法:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

handleException方法就會丟擲所有control層丟擲的異常,這是最簡單的demo

同時在@ExceptionHandler中也可以自定義一些異常,比如說我定義一個業務異常

public class BussinessException extends RuntimeException {
    public BussinessException(Throwable e) {
        super(e.getMessage(), e);
    }
}

使用這個異常:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BussinessException.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

舉例我們有一個service

public class TestService {

   
    public POP update(POP pop){

        ....

        ....
        if(...){
        BSUtil.isTrue(false);
        }
        // ......

        return null;
    }

}

自定義一個BSUtil

public static void isTrue(boolean expression){
    if(!expression) {
        throw new BusinessException(error);
    }
}

當我們的control層去使用這個TestServer的時候我們不用去寫trycatch就可以丟擲我們自定義的異常了

其實,被 @ExceptionHandler 註解的方法還可以宣告很多引數,詳見文件。