在底層框架(jia)使(shi)用@SneakyThrows注解
@SneakyThrows注解是由lombok為我們封裝的,它可以為我們的代碼生成一個try...catch塊,并把異常向上拋出來,而你之前的ex.getStackTrace()是沒(mei)有這(zhe)種能力的(de),有時,我們從底層(ceng)拋出的(de)異(yi)常(chang)需要被(bei)上層(ceng)統一收集,而又(you)不想在底層(ceng)new出一大堆業(ye)務相(xiang)關的(de)異(yi)常(chang)實例,這(zhe)時使用@SneakyThrows可以簡化我們的(de)代碼(ma)。
@SneakyThrows為方法添加注解
import lombok.SneakyThrows;
public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
@SneakyThrows
public void run() {
throw new Throwable();
}
}
而它生(sheng)成的(de)代碼(ma)為我(wo)們加上(shang)了try...cache塊(kuai),并以新的(de)Lombok.sneakyThrow的(de)方式向上(shang)拋出
import lombok.Lombok;
public class SneakyThrowsExample implements Runnable {
public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);
}
}
public void run() {
try {
throw new Throwable();
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
}
而這(zhe)種方法(fa),在上層被(bei)(bei)調用時,它(ta)產生(sheng)的異常是可以(yi)被(bei)(bei)向(xiang)上傳遞的,并且對它(ta)進行業(ye)務(wu)(wu)上的封裝(zhuang),產生(sheng)業(ye)務(wu)(wu)相關的異常消息
throw new RepeatSubmitException(
String.format("記錄正被用戶%s鎖定,將在%s秒后釋放",
currentValue,
redisTemplate.getExpire(key)));
而在上層通過 @RestControllerAdvice和ExceptionHandler進行統一的捕獲即可
@ExceptionHandler(RepeatSubmitException.class)
@ResponseStatus(HttpStatus.OK)
public CommonResult<String> handlerIllegalArgumentException(IllegalArgumentException e) {
String message = e.getMessage();
log.error(message);
return CommonResult.failure(400,message);
}
