01
自定義異常類
異常處理常用方法:
常用的異常處理方法有:
try()catch() 語句
throw / throws 語句
自定義異常類
簡要介紹
繼承Throwable
繼承Exception
繼承RuntimeException
將 Controller 層的異常和Service的異常進行統一處理,封裝成自定義的異常
注意spring中,只有繼承RuntimeException才會進行事務回滾,Exception不會進行事務回滾
一般會選擇繼承Exception和RuntimeException,如果不要求呼叫者一定要處理丟擲的異常,就繼承RuntimeException。
@Getter
public
class
BusinessException
extends
RuntimeException
{
private
static
final
long
serialVersionUID = -
3197885623427623567L
;
private
Integer code;
private
String msg;
public
BusinessException
(ResultCodeEnum ResultCodeEnum, Object msg) {
this
。code=ResultCodeEnum。getCode();
if
(msg!=
null
){
this
。msg=msg。toString();
}
else
{
this
。msg=ResultCodeEnum。getMsg();
}
}
public
BusinessException
(ResultCodeEnum ResultCodeEnum) {
this
。code=ResultCodeEnum。getCode();
this
。msg=ResultCodeEnum。getMsg();
}
}
02
@RestControllerAdvice+@ExceptionHandler
簡要介紹
捕獲全域性的異常進行統一處理,減少模板程式碼,減少編碼量,提升擴充套件性和可維護性
@RestControllerAdvice(basePackages = {“com。example。demo”})@Slf4jpublic class ExceptionHandle { @ExceptionHandler(BusinessException。class) public ReponseResult businessExceptionHandler(BusinessException e){ log。error(“BusinessException異常資訊:{}”,e); return new ReponseResult(e。getCode(),e。getMsg(),null); } @ExceptionHandler(Exception。class) public ReponseResult defaultExceptionHandler(Exception e){ log。error(“defaultExceptionHandler異常資訊:{}”,e); return new ReponseResult(ResultCodeEnum。FAIL,e,null); }}
03
效果展示