日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

java异常自定义返回信息,Spring Boot 如何自定义返回错误码错误信息

發布時間:2025/3/8 javascript 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java异常自定义返回信息,Spring Boot 如何自定义返回错误码错误信息 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

說明

在實際的開發過程中,很多時候要定義符合自己業務的錯誤碼和錯誤信息,而不是統一的而不是統一的下面這種格式返回到調用端

INTERNAL_SERVER_ERROR(500, "Internal Server Error"),

下面我們來看看如何將我們自定義的錯誤碼和錯誤信息返回到調用端。

1 自定義錯誤碼

首先我們要定義一個枚舉類

public enum ErrorEnum {

/*

* 錯誤信息

* */

E_20011(20011, "缺少必填參數"),

;

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;

}

2 定義一個異常類

定義一個異常類繼承RuntimeException類

public class BusinessException extends RuntimeException {

private static final long serialVersionUID = 1L;

private Integer code;

/**

* @param errorEnum 以錯誤的ErrorEnum做參數

*/

public BusinessException(ErrorEnum errorEnum) {

super(errorEnum.getErrorMsg());

this.code = errorEnum.getErrorCode();

this.resultJson = CommonUtil.errorJson(errorEnum);

}

public Integer getCode() {

return code;

}

public void setCode(Integer code) {

this.code = code;

}

}

3 定義一個異常返回的模板類

模板類定義了如何將異常通過什么形式進行返回。

public class ExceptionResponse {

private String message;

private Integer code;

public ExceptionResponse(Integer code, String message) {

this.message = message;

this.code = code;

}

public static ExceptionResponse create(Integer code, String message) {

return new ExceptionResponse(code, message);

}

public Integer getCode() {

return code;

}

public String getMessage() {

return message;

}

}

4 定義全局處理 Controller 層異常

@ControllerAdvice

@Slf4j

public class ExceptionHandler {

@ResponseBody

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

@ExceptionHandler(Exception.class)

public ExceptionResponse handleException(Exception ex) {

if (ex instanceof BusinessException) {

log.warn(ex.getMessage(), ex);

BusinessException businessException = (BusinessException) ex;

return ExceptionResponse.create(businessException.getCode(), businessException.getMessage());

} else {

log.error(ex.getMessage(), ex);

return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());

}

}

}

5 演示效果

定義Controller層

@PostMapping("test/exception")

public String testException() {

throw new BusinessException(ErrorEnum.E_20011);

}

通過postMan調用返回結果為

{ "message": "缺少必填參數", "code": 20011 }

總結

以上是生活随笔為你收集整理的java异常自定义返回信息,Spring Boot 如何自定义返回错误码错误信息的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。