前言
軟件開發springboot項目過程中,不可避免的需要處理各種異常,spring mvc 架構中各層會出現大量的try {...} catch {...} finally {...} 代碼塊,不僅有大量的冗餘代碼,而且還影響代碼的可讀性。這樣就需要定義個全局統一異常處理器,以便業務層再也不必處理異常。
推薦理由
- 代碼複製到項目中通過簡單的配置即可實現
- 可以靈活的根據自己的業務異常進行更細粒度的擴展
實踐
1 封裝統一返回結果類
圖片
源代碼
<code>public
class
AjaxResult
{private
Boolean
success;private
Integer code;private
String msg;private
Objectdata
;public
AjaxResult() { }public
AjaxResult(Boolean
success,Integer code, String msg,Objectdata
) {this
.success = success;this
.code = code;this
.msg = msg;this
.data
=data
; }public
static AjaxResult defineError(BusinessException de){ AjaxResult result = new AjaxResult(); result.setSuccess(false
); result.setCode(de.getErrorCode()); result.setMsg(de.getErrorMsg()); result.setData(null
);return
result; }public
static AjaxResult otherError(ErrorEnum errorEnum){ AjaxResult result = new AjaxResult(); result.setMsg(errorEnum.getErrorMsg()); result.setCode(errorEnum.getErrorCode()); result.setSuccess(false
); result.setData(null
);return
result; }public
Boolean
getSuccess() {return
success; }public
void setSuccess(Boolean
success) {this
.success = success; }public
Integer getCode() {return
code; }public
void setCode(Integer code) {this
.code = code; }public
String getMsg() {return
msg; }public
void setMsg(String msg) {this
.msg = msg; }public
Object getData() {return
data
; }public
void setData(Objectdata
) {this
.data
=data
; } }/<code>
2 自定義異常封裝類
源碼:
<code>public
class
BusinessException
extends
RuntimeException
{private
static
final
long
serialVersionUID =1L
;protected
Integer errorCode;protected
String errorMsg;public
BusinessException
()
{ }public
BusinessException
(Integer errorCode, String errorMsg)
{this
.errorCode = errorCode;this
.errorMsg = errorMsg; }public
IntegergetErrorCode
()
{return
errorCode; }public
void
setErrorCode
(Integer errorCode)
{this
.errorCode = errorCode; }public
StringgetErrorMsg
()
{return
errorMsg; }public
void
setErrorMsg
(String errorMsg)
{this
.errorMsg = errorMsg; } }/<code>
3 錯誤枚舉,拒絕硬編碼
源碼
<code>public
enum
ErrorEnum { SUCCESS(200
,"成功"
), NO_PERMISSION(403
,"你沒得權限"
), NO_AUTH(401
,"未登錄"
), NOT_FOUND(404
,"未找到該資源!"
), INTERNAL_SERVER_ERROR(500
,"服務器異常請聯繫管理員"
), ;private
Integer errorCode;private
String
errorMsg; ErrorEnum(Integer errorCode,String
errorMsg) {this
.errorCode = errorCode;this
.errorMsg = errorMsg; }public
Integer getErrorCode() {return
errorCode; }public
String
getErrorMsg() {return
errorMsg; } }/<code>
4 全局異常處理類
源碼
<code> @RestControllerAdvicepublic
class
GlobalExceptionHandler
{private
static
final
Loggerlog
= LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = BusinessException.class)public
AjaxResultbizExceptionHandler
(BusinessException e)
{log
.error(e.getMessage(), e);return
AjaxResult.defineError(e); } @ExceptionHandler(value = Exception.class)public
AjaxResultexceptionHandler
( Exception e)
{log
.error(e.getMessage(), e);return
AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR); } }/<code>
5 測試
返回結果: