網站首頁 編程語言 正文
1.定義基礎異常接口類
/**
* @description: 服務接口類
* @author: MrVK
* @date: 2021/4/19 21:39
*/
public interface BaseErrorInfoInterface {
/**
* 錯誤碼
* @return
*/
String getResultCode();
/**
* 錯誤描述
* @return
*/
String getResultMsg();
}
2.定義錯誤處理枚舉類
/**
* @description: 異常處理枚舉類
* @author: MrVK
* @date: 2021/4/19 21:41
* @version: v1.0
*/
public enum ExceptionEnum implements BaseErrorInfoInterface{
// 數據操作錯誤定義
SUCCESS("2000", "成功!"),
BODY_NOT_MATCH("4000","請求的數據格式不符!"),
SIGNATURE_NOT_MATCH("4001","請求的數字簽名不匹配!"),
NOT_FOUND("4004", "未找到該資源!"),
INTERNAL_SERVER_ERROR("5000", "服務器內部錯誤!"),
SERVER_BUSY("5003","服務器正忙,請稍后再試!");
/**
* 錯誤碼
*/
private final String resultCode;
/**
* 錯誤描述
*/
private final String resultMsg;
ExceptionEnum(String resultCode, String resultMsg) {
this.resultCode = resultCode;
this.resultMsg = resultMsg;
}
@Override
public String getResultCode() {
return resultCode;
}
@Override
public String getResultMsg() {
return resultMsg;
}
}
3.自定義異常類
/**
* @description: 自定義異常類
* @author: MrVK
* @date: 2021/4/19 21:44
* @version: v1.0
*/
public class BizException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* 錯誤碼
*/
protected String errorCode;
/**
* 錯誤信息
*/
protected String errorMsg;
public BizException() {
super();
}
public BizException(BaseErrorInfoInterface errorInfoInterface) {
super(errorInfoInterface.getResultCode());
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}
public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
super(errorInfoInterface.getResultCode(), cause);
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}
public BizException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public BizException(String errorCode, String errorMsg) {
super(errorCode);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public BizException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
4.自定義響應體類
/**
* @description: 自定義數據傳輸
* @author: MrVK
* @date: 2021/4/19 21:47
* @version: v1.0
*/
public class ResultResponse {
/**
* 響應代碼
*/
private String code;
/**
* 響應消息
*/
private String message;
/**
* 響應結果
*/
private Object result;
public ResultResponse() {
}
public ResultResponse(BaseErrorInfoInterface errorInfo) {
this.code = errorInfo.getResultCode();
this.message = errorInfo.getResultMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
/**
* 成功
*
* @return
*/
public static ResultResponse success() {
return success(null);
}
/**
* 成功
* @param data
* @return
*/
public static ResultResponse success(Object data) {
ResultResponse rb = new ResultResponse();
rb.setCode(ExceptionEnum.SUCCESS.getResultCode());
rb.setMessage(ExceptionEnum.SUCCESS.getResultMsg());
rb.setResult(data);
return rb;
}
/**
* 失敗
*/
public static ResultResponse error(BaseErrorInfoInterface errorInfo) {
ResultResponse rb = new ResultResponse();
rb.setCode(errorInfo.getResultCode());
rb.setMessage(errorInfo.getResultMsg());
rb.setResult(null);
return rb;
}
/**
* 失敗
*/
public static ResultResponse error(String code, String message) {
ResultResponse rb = new ResultResponse();
rb.setCode(code);
rb.setMessage(message);
rb.setResult(null);
return rb;
}
/**
* 失敗
*/
public static ResultResponse error( String message) {
ResultResponse rb = new ResultResponse();
rb.setCode("-1");
rb.setMessage(message);
rb.setResult(null);
return rb;
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
5.自定義全局異常處理
/**
* @description: 自定義異常處理
* @author: MrVK
* @date: 2021/4/19 21:51
* @version: v1.0
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 處理自定義的業務異常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = BizException.class)
@ResponseBody
public ResultResponse bizExceptionHandler(HttpServletRequest req, BizException e){
logger.error("發生業務異常!原因是:{}",e.getErrorMsg());
return ResultResponse.error(e.getErrorCode(),e.getErrorMsg());
}
/**
* 處理空指針的異常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =NullPointerException.class)
@ResponseBody
public ResultResponse exceptionHandler(HttpServletRequest req, NullPointerException e){
logger.error("發生空指針異常!原因是:",e);
return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
}
/**
* 處理其他異常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public ResultResponse exceptionHandler(HttpServletRequest req, Exception e){
logger.error("未知異常!原因是:",e);
return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
}
}
6.測試代碼
@PostMapping("/add")
public boolean add(@RequestBody User user) {
//如果姓名為空就手動拋出一個自定義的異常!
if(user.getName()==null){
throw new BizException("-1","用戶姓名不能為空!");
}
return true;
}
@PutMapping("/update")
public boolean update(@RequestBody User user) {
//這里故意造成一個空指針的異常,并且不進行處理
String str = null;
str.equals("111");
return true;
}
@DeleteMapping("/delete")
public boolean delete(@RequestBody User user) {
//這里故意造成一個異常,并且不進行處理
Integer.parseInt("abc123");
return true;
}
@GetMapping("/error")
@ExceptionHandler(value = NumberFormatException.class)
@ResponseBody
public ResultResponse exceptionHandler(HttpServletRequest req, NumberFormatException e){
logger.error("發生類型轉換異常!原因是:",e);
return ResultResponse.error(ExceptionEnum.PARAMS_NOT_CONVERT);
}
7.測試結果
原文鏈接:https://blog.csdn.net/Mr_VK/article/details/136438289
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-02-27 Python使用Crypto庫實現加密解密的示例詳解_python
- 2022-06-12 C語言實例真題講解數據結構中單向環形鏈表_C 語言
- 2022-12-06 nginx?pod?hook鉤子優雅關閉示例詳解_nginx
- 2022-07-03 C#列表List<T>、HashSet和只讀集合介紹_C#教程
- 2022-04-23 .NET?Core使用APB?vNext框架入門教程_實用技巧
- 2022-07-02 Prometheus+Grafana監控Docker容器和Linux主機
- 2022-11-12 golang?goquery?selector選擇器使用示例大全_Golang
- 2022-08-20 Matlab操作HDF5文件示例_相關技巧
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支