@SneakyThrows注解是由lombok為我們封裝的,它可以為我們的代碼生成一個try...catch塊,並把異常向上拋出來,而你之前的ex.getStackTrace()
是沒有這種能力的,有時,我們從底層拋出的異常需要被上層統一收集,而又不想在底層new出一大堆業務相關的異常實例,這時使用@SneakyThrows可以簡化我們的代碼。
@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();
}
}
而它生成的代碼為我們加上了try...cache塊,並以新的Lombok.sneakyThrow的方式向上拋出
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);
}
}
}
而這種方法,在上層被調用時,它產生的異常是可以被向上傳遞的,並且對它進行業務上的封裝,產生業務相關的異常消息
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);
}