【1】创建全局异常的类
BusinessException
@Slf4j
public class BusinessException extends RuntimeException {
/**
* 错误码
*/
private int code;
public int getCode() {
return code;
}
/**
* @param message
*/
public BusinessException(String message) {
super(message);
this.code = CommonResult.SYSTEM_ERROR.getCode();
}
/**
* @param code
* @param message
*/
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
/**
* @param message
* @param cause
*/
public BusinessException(String message, Throwable cause) {
super(message, cause);
this.code = CommonResult.SYSTEM_ERROR.getCode();
}
}
【2】 全局异常处理 GlobalExceptionHandler
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author ****
* @description 全局异常处理
* @date 2024年05月08日 13:46
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseEntity<ErrorResponse> handleException(Exception e) {
// 如果是自定义异常,可以从中获取errorCode
int errorCode = e instanceof BusinessException ? ((BusinessException) e).getCode() : 500;
String errorMessage = e.getMessage();
String detailMessage = e.getLocalizedMessage();
// 特殊的异常 token失效 401
if (errorCode == CommonResult.TOKEN_INVALID.getCode()) {
ErrorResponse errorResponse = new ErrorResponse(CommonResult.TOKEN_INVALID.getCode(), "Token令牌失效", "Token令牌失效");
errorResponse.setMessage(errorMessage); // 设置错误信息
return new ResponseEntity(errorResponse, HttpStatus.UNAUTHORIZED);
} else {
// 一般的异常 500
ErrorResponse errorResponse = new ErrorResponse(errorCode, errorMessage, detailMessage);
errorResponse.setMessage(errorMessage);
errorResponse.setDetailMessage(detailMessage);
errorResponse.setCode(errorCode);
return new ResponseEntity(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// 如果有其他需要特殊处理的异常类型,可以添加更多的@ExceptionHandler方法
}
【3】异常返回
import lombok.Data;
/**
* @author ****
* @description 定义统一的错误响应格式
* @date 2024年05月08日 13:40
*/
@Data
public class ErrorResponse {
/**
* 错误码
*/
private int code;
/**
* 消息
*/
private String message;
/**
* 可选,用于包含更详细的错误信息
*/
private String detailMessage;
public ErrorResponse(int errorCode, String message,String detailMessage)
{
this.code = errorCode;
this.message = message;
this.detailMessage = detailMessage;
}
}
【4】Service里面使用示例
throw new BusinessException(500, "系统异常:没有配置系统参数");
其他的异常也会按照500输出