第一步:先写一个异常管理类:
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