第一步:先寫一個異常管理類:
package com.example.firefighting.exceptions;import com.example.firefighting.utils.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import static com.example.firefighting.utils.XiaofangConstants.SYSTEM_ANOMALY;/*** 異常處理* @author IT空門_門主* @date 2024/7/2*/@RestControllerAdvice
public class XiaofangException {/*** 全局異常*/@ExceptionHandler(value = Exception.class)public Result globalException() {return Result.fail(SYSTEM_ANOMALY);}/*** 業務異常處理* @param e* @return*/@ExceptionHandler(value = ServiceException.class)public Result serviceException(ServiceException e) {return Result.fail(e.getCode(), e.getMessage());}}
- 我這里定義了兩個異常:一個是全局異常和業務的異常。 項目大的情況下可以自定義更多的異常
第二步:業務的異常繼承了運行異常
package com.example.firefighting.exceptions;import lombok.Data;
import lombok.EqualsAndHashCode;/*** 業務邏輯異常 Exception*/
@Data
@EqualsAndHashCode(callSuper = true)
public final class ServiceException extends RuntimeException {/*** 業務錯誤碼*/private Integer code;/*** 錯誤提示*/private String message;public ServiceException(Integer code, String message) {this.code = code;this.message = message;}}
- 業務的異常中,可以通過自己的業務,編寫自己的業務邏輯。
- 我是為了統一管理業務錯誤,編寫了有參構造接收錯誤信息
第三步:工具類
package com.example.firefighting.exceptions.utils;import com.example.firefighting.exceptions.ServiceException;
import com.example.firefighting.utils.ErrorCode;import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;/*** @author IT空門_門主* @description: 自定義異常工具類* @date 2024/7/2*/public class ServiceExceptionUtil {/*** 錯誤碼提示模板*/private static final ConcurrentMap<Integer, String> MESSAGES = new ConcurrentHashMap<>();/*** 自定義異常*/public static ServiceException exception(ErrorCode errorCode) {String messagePattern = MESSAGES.getOrDefault(errorCode.getCode(), errorCode.getMsg());return exception0(errorCode.getCode(), messagePattern);}private static ServiceException exception0(Integer code, String messagePattern) {return new ServiceException(code, messagePattern);}}
1.ConcurrentHashMap:
用于多線程環境,允許多個線程同時讀寫映射而不會引起數據不一致的問題。ConcurrentHashMap是ConcurrentMap的一個實現,提供了高效的并發性能。
第四步:錯誤枚舉
package com.example.firefighting.enums;import com.example.firefighting.utils.ErrorCode;/*** 錯誤碼枚舉類* device 系統 從 1001開始-9999結束 不可重復* @author IT空門_門主* @date 2024/7/2*/public interface ErrorCodeConstants {ErrorCode USER_DOES_NOT_EXIST = new ErrorCode(1001, "該用戶不存在");ErrorCode USER_IS_DISABLED = new ErrorCode(1002, "該用戶已被禁用");ErrorCode INCORRECT_USERNAME_OR_PASSWORD = new ErrorCode(1003, "用戶名或密碼錯誤");
}
1.管理業務所有的錯誤碼
商務合作:z13135361785??
技術交流:z13135361785??