斷言+異常處理類,代碼更簡潔了
閱讀本文大概需要 7 分鐘。
來自:https://c1n.cn/E6fZj
背景
業(yè)務(wù)異常處理示例
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
private static final long serialVersionUID = 411731814484355577L;
private int responseCode;
private String responseMsg;
private boolean isSuccess;
private T data;
public String toString() {
return "ApiResult(responseCode=" + this.getResponseCode() + ", responseMsg=" + this.getResponseMsg() + ", isSuccess=" + this.isSuccess() + ", data=" + this.getData() + ")";
}
}
public ApiResult cancelService(@PathVariable Long serviceOrderId){
ServiceOrder serviceOrder = serviceOrderMapper.selectByPrimaryKey(serviceOrderId);
ApiResult result = new ApiResult<>();
if (ObjectUtil.isNull(serviceOrder)) {
result.setSuccess(false);
result.setResponseCode(ErrorCodeEnum.FAIL.getCode());
result.setResponseMsg("查無此服務(wù)單");
return result;
}
if(serviceOrder.getOrderStatus().equals(cancelOrderStatus)){
result.setSuccess(false);
result.setResponseCode(ErrorCodeEnum.FAIL.getCode());
result.setResponseMsg("已取消的服務(wù)單不允許再次取消");
return result;
}
if(serviceOrder.getSortOrderId() != null){
result.setSuccess(false);
result.setResponseCode(ErrorCodeEnum.FAIL.getCode());
result.setResponseMsg("已配置物料的服務(wù)單不允許取消");
return result;
}
// ...other check
// ...do something
return result;
}
public static ApiResult<String> success() {
return success("success");
}
public static <T> ApiResult<T> success(T data) {
return (new ApiResult()).setResponseCode(0).setResponseMsg("操作成功").setSuccess(true).setData(data);
}
public static ApiResult<String> fail() {
return fail(-1);
}
public static ApiResult<String> fail(int code) {
return fail(code, "fail");
}
public static <T> ApiResult<T> fail(T data) {
return fail(-1, data);
}
public static <T> ApiResult<T> fail(int code, T data) {
return (new ApiResult()).setResponseCode(code).setResponseMsg("操作失敗").setSuccess(false).setData(data);
}
public static <T> ApiResult<T> success(int code, String message, T data) {
return (new ApiResult()).setResponseCode(code).setResponseMsg(message).setSuccess(true).setData(data);
}
public static <T> ApiResult<T> fail(int code, String message, T data) {
return (new ApiResult()).setResponseCode(code).setResponseMsg(message).setSuccess(false).setData(data);
}
/**
* 取消服務(wù)單(不用斷言)
*/
public ApiResult cancelService(Long serviceOrderId){
ServiceOrder serviceOrder = serviceOrderMapper.selectByPrimaryKey(serviceOrderId);
ApiResult result = new ApiResult<>();
if (ObjectUtil.isNull(serviceOrder)) {
result = ApiResult.fail(ErrorCodeEnum.FAIL.getCode(), "查無此服務(wù)單");
return result;
}
if(serviceOrder.getOrderStatus().equals(cancelOrderStatus)){
result = ApiResult.fail(ErrorCodeEnum.FAIL.getCode(), "已取消的服務(wù)單不允許再次取消");
return result;
}
if(serviceOrder.getSortOrderId() != null){
result = ApiResult.fail(ErrorCodeEnum.FAIL.getCode(), "已配置物料的服務(wù)單不允許取消");
return result;
}
// ...other check
// ...do something
return result;
}
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ResponseBean businessExceptionHandler(BusinessException e) {
log.info("business error : {}",e.getMessage(),e);
if (e.getCode() == -1) {
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), ApiCode.SERVICE_ERROR.getMessage());
}
return ResponseBean.error(e.getCode(), e.getMessage());
}
}
/**
* 業(yè)務(wù)異常,異常信息會返回到前端展示給用戶
*
* @date 2020/12/15 14:18
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = -5770538329754222306L;
private int code = 1;
private Level level;
public BusinessException(int code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public BusinessException(String message) {
super(message);
}
public BusinessException(Level level, String message) {
super(message);
this.level = level;
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return this.code;
}
public final Level getLevel() {
return this.level;
}
}
public class AssertUtil extends cn.com.bluemoon.common.web.exception.AssertUtil {
public AssertUtil() {
}
/**
* 服務(wù)調(diào)用異常
* @param expression
* @param message
*/
public static void isTrueServiceInvoke(boolean expression, String message) {
if (!expression) {
throw new ServiceInvokeException(message);
}
}
/**
* 拋出異常(默認錯誤1000)
* @param message
*/
public static void businessInvalid(String message) {
throw new BusinessException(ApiCode.SERVICE_ERROR.getValue(), message);
}
/**
* 表達式為真即拋出異常(默認錯誤1000)
*
* @param expression
* @param message
*/
public static void businessInvalid(boolean expression, String message) {
if (expression) {
throw new BusinessException(ApiCode.SERVICE_ERROR.getValue(), message);
}
}
/**
* 表達式為真即拋出異常
*
* @param expression
* @param message
*/
public static void businessInvalid(boolean expression, int code, String message) {
if (expression) {
throw new BusinessException(code, message);
}
}
}
/**
* 取消服務(wù)單
*/
public ApiResult cancelService(@PathVariable Long serviceOrderId){
ServiceOrder serviceOrder = serviceOrderMapper.selectByPrimaryKey(serviceOrderId);
AssertUtil.businessInvalid(ObjectUtil.isNull(serviceOrder),"查無此服務(wù)單");
AssertUtil.businessInvalid(serviceOrder.getOrderStatus().equals(cancelOrderStatus),"查無此服務(wù)單");
AssertUtil.businessInvalid(serviceOrder.getSortOrderId() != null,"查無此服務(wù)單");
// ...other check
// ...do something
return ApiResult.success();
}
附上代碼
/**
* 統(tǒng)一異常處理
*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = AssertException.class)
@ResponseBody
public ResponseBean bootExceptionHandler(AssertException e) {
ApiCode apiCode = ApiCode.getObjectByValue(e.getCode());
log.error("business error : {}", e.getMessage(), e);
if (e.getCode() == -1) {
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), ApiCode.SERVICE_ERROR.getMessage());
}
return ResponseBean.error(apiCode.getValue(), e.getMessage());
}
@ExceptionHandler(value = com.alibaba.fastjson.JSONException.class)
public ResponseBean alibabaJsonExceptionHandler(com.alibaba.fastjson.JSONException e) {
ResponseBean response = new ResponseBean(false, ApiCode.PARAM_FORMAT_INCORR.getValue(), ApiCode.PARAM_FORMAT_INCORR.getMessage() + e.getMessage(), null);
log.error("1102", e);
return response;
}
@ExceptionHandler(value = JSONException.class)
@ResponseBody
public ResponseBean jsonExceptionHandler(JSONException e) {
ResponseBean response = new ResponseBean(false, ApiCode.PARAM_FORMAT_INCORR.getValue(), ApiCode.PARAM_FORMAT_INCORR.getMessage() + e.getMessage(), null);
log.error(ApiCode.PARAM_FORMAT_INCORR.getValue() + "", e);
return response;
}
@ExceptionHandler(value = JsonParseException.class)
@ResponseBody
public ResponseBean jsonParseExceptionHandler(JsonParseException e) {
ResponseBean response = new ResponseBean(false, ApiCode.PARAM_FORMAT_INCORR.getValue(), String.format(ApiCode.PARAM_FORMAT_INCORR.getMessage() + ":%s", e.getMessage()), null);
log.error(ApiCode.PARAM_FORMAT_INCORR.getValue() + "", e);
return response;
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseBean exceptionHandler(Exception e) {
ResponseBean response = new ResponseBean(false, ApiCode.SERVICE_ERROR.getValue(), ApiCode.SERVICE_ERROR.getMessage(), null);
log.error(ApiCode.SERVICE_ERROR.getValue() + "", e);
return response;
}
@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
@ResponseBody
public ResponseBean exceptionHandle(MethodArgumentTypeMismatchException e) {
ResponseBean response = new ResponseBean(false, ApiCode.PARAM_FORMAT_INCORR.getValue(), String.format(ApiCode.PARAM_FORMAT_INCORR.getMessage() + ":%s", e.getMessage()), null);
log.error(ApiCode.PARAM_FORMAT_INCORR.getValue() + "", e);
return response;
}
@ExceptionHandler(value = WebException.class)
@ResponseBody
public ResponseBean exceptionHandler(WebException e) {
ResponseBean response = new ResponseBean(e.getIsSuccess(), e.getResponseCode(), e.getResponseMsg(), null);
log.error(e.getResponseCode() + "", e);
return response;
}
@ExceptionHandler(value = IllegalArgumentException.class)
@ResponseBody
public ResponseBean exceptionHandler(IllegalArgumentException e) {
log.error("illegal request : {}", e.getMessage(), e);
return ResponseBean.error(ApiCode.PARAM_INVALID.getValue(), ApiCode.PARAM_INVALID.getMessage());
}
@ExceptionHandler(value = ServiceInvokeException.class)
@ResponseBody
public ResponseBean exceptionHandler(ServiceInvokeException e) {
log.error("serviceInvoke error request : {}", e.getMessage(), e);
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), ApiCode.SERVICE_ERROR.getMessage());
}
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ResponseBean businessExceptionHandler(BusinessException e) {
log.info("business error : {}",e.getMessage(),e);
if (e.getCode() == -1) {
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), ApiCode.SERVICE_ERROR.getMessage());
}
return ResponseBean.error(e.getCode(), e.getMessage());
}
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseBean exceptionHandler(MethodArgumentNotValidException e) {
log.info("req params error", e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
if (StringUtils.isNotBlank(message) && !"不能為空".equals(message)) {
return ResponseBean.error(ApiCode.PARAM_INVALID.getValue(), message);
}
return ResponseBean.error(ApiCode.PARAM_INVALID.getValue(), ApiCode.PARAM_INVALID.getMessage());
}
@ExceptionHandler(value = TokenErrorException.class)
@ResponseBody
public ResponseBean tokenErrorExceptionHandler(TokenErrorException e) {
log.info("登錄失效 : {}",e.getMessage(),e);
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), "登錄已失效,請重新登錄!");
}
@ExceptionHandler(value = ServiceException.class)
@ResponseBody
public ResponseBean businessExceptionHandler(ServiceException e) {
log.info("service error : {}",e.getMessage(),e);
return ResponseBean.error(ApiCode.SERVICE_ERROR.getValue(), e.getMessage());
}
}
public enum ErrorCodeEnum implements EnumBase{
FAIL(-1, "網(wǎng)絡(luò)異常,請稍后再試"),
SUCCESS(0, "請求成功"),
MAX_UPLOAD_SIZE_ERROR(1000, "上傳文件不能超過20M"),
SERVICE_BUSY_ERROR(1000, "服務(wù)器正在繁忙,請稍后再試哦~"),
REQUEST_PARAMS_FAIL(1001, "參數(shù)錯誤"),
USER_NOT_LOGIN(1002, "用戶未登錄,請重新登錄"),
USER_HAS_EXIST_LOGIN(1007, "用戶已經(jīng)存在,請檢查!"),
USER_CODE_NOT_EXIST(1008, "用戶編碼不存在,請檢查!"),
REQUEST_PARAMS_FORMAT_ERROR(1102, "請求參數(shù)格式異常"),
PASSWORD_SAFETY_ERROE(2204, "密碼不符合安全規(guī)則,請通過忘記密碼重新設(shè)置8-18位數(shù)字+字母組合密碼"),
TOKEN_EXPIRED(2301, "token過期"),
TOKEN_ERROR(2302, "token驗證失敗"),
INTERFACE_ERROR(10000, "接口服務(wù)器異常");
private final int code;
private final String msg;
ErrorCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public int getCode() {
return this.code;
}
@Override
public String getMsg() {
return this.msg;
}
}
推薦閱讀:
重磅:國產(chǎn)IDE發(fā)布,由阿里研發(fā),完全開源!(高性能+高定制性)
利用 Redis 的 sorted set 做每周熱評的功能
互聯(lián)網(wǎng)初中高級大廠面試題(9個G) 內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!
?戳閱讀原文領(lǐng)取! 朕已閱
評論
圖片
表情


