四. 统一API响应体与全局异常拦截器的封装配置

2022-12-27 15:55:57 浏览数 (1)

API响应体的统一

引入lombok依赖

代码语言:javascript复制
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

响应体POJO类

主要实现统一响应体返回格式

代码语言:javascript复制
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseResponse<T> {
    private String code;
    private String message;
    private T data;
    
}

响应体枚举类

BaseCodeEnum

代码语言:javascript复制
public enum BaseCodeEnum implements BaseCodeInfoInterface {
    SUCCESS("200","成功!"),
    BOOY_NOT_MATCH("400","数据格式不匹配或参数异常"),
    NO_AUTHORIZED("401","未查询到登录信息或无权进行此操作"),
    NOT_FOUND("404","访问资源不存在"),
    INTERNAL_SERVER_ERROR("500","服务器内部错误"),
    ASSERT("400","ASSERT抛出异常!");


    private String code;
    private String message;

    BaseCodeEnum(String code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }


    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

枚举接口类

BaseCodeInfoInterface

代码语言:javascript复制
public interface BaseCodeInfoInterface {
    String getCode();
    String getMessage();
}

响应体调用方法封装

RespGenerator

代码语言:javascript复制
public class RespGenerator {
//    正常返回调用接口
    public static BaseResponse success(Object data){
        return new BaseResponse(BaseCodeEnum.SUCCESS.getCode(),"接口调用成功",data);
    }

    //    正常返回调用接口(无参)
    public static BaseResponse success_noData(String msg){
        return new BaseResponse(BaseCodeEnum.SUCCESS.getCode(),msg,null);
    }


//    失败调用(入参异常枚举)
    public static  BaseResponse<Object> fail(BaseCodeEnum baseErrorEnum){
        return new BaseResponse<Object>(baseErrorEnum.getCode(),baseErrorEnum.getMessage(),null);
    }

//    调用失败
    public static  BaseResponse<Object> fail(String code,String message){
        System.out.println(new BaseResponse<Object>(code,message,null).toString());
        return new BaseResponse<Object>(code,message,null);
    }
}

全局统一异常处理

项目开发中经常会用到很多try catch代码块,然而使用过多会显得项目臃肿且不利于项目的可读性与维护性。

全局异常拦截器类

GlobalExceptionHandler

代码语言:javascript复制
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Log logger = LogFactory.getLog(cc.tanblog.online.config.GlobalExceptionHandler.class);

//    处理自定义异常
    @ExceptionHandler(value = BaseException.class)
    public BaseResponse<Object> baseExceptionHandler(BaseException e){
        logger.error("发生自定义异常!原因是:" e.getMessage());
        return RespGenerator.fail(e.getCode(),e.getMessage());
    }

    //    处理空指针异常
    @ExceptionHandler(value = NullPointerException.class)
    public BaseResponse<Object> exceptionHandler(NullPointerException e){
        logger.error("发生业务异常!原因是:" e.getMessage());
        return RespGenerator.fail(BaseCodeEnum.BOOY_NOT_MATCH);
    }

    //    处理断言异常
    @ExceptionHandler(value = IllegalArgumentException.class)
    public BaseResponse<Object> exceptionHandler(IllegalArgumentException e){
        logger.error("assert抛出异常。原因是:" e.getMessage());
        BaseCodeEnum.ASSERT.setMessage(e.getMessage());
        return RespGenerator.fail(BaseCodeEnum.ASSERT);
    }

            //    参数为空异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResponse<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e){
        logger.error("参数异常:" e.getBindingResult().getFieldError().getDefaultMessage());
        BaseCodeEnum.BOOY_NOT_MATCH.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return RespGenerator.fail(BaseCodeEnum.BOOY_NOT_MATCH);
    }

//    HttpRequestMethodNotSupportedException    404
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public BaseResponse<Object> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        logger.error("assert抛出异常。原因是:" e.getMessage());
        BaseCodeEnum.ASSERT.setMessage(e.getMessage());
        return RespGenerator.fail(BaseCodeEnum.ASSERT);
    }
//    DataIntegrityViolationException

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public BaseResponse<Object> DataIntegrityViolationException(DataIntegrityViolationException e){
        logger.error("数据库异常操作");
        BaseCodeEnum.ASSERT.setMessage("主键异常");
        return RespGenerator.fail(BaseCodeEnum.ASSERT);
    }
    
    //    全部异常拦截处理
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<Object> exceptionHandler(Exception e){
        logger.error("发生服务器内部未知错误,请联系管理员处理。错误原因为:",e);
        BaseCodeEnum.INTERNAL_SERVER_ERROR.setMessage("发生服务器内部未知错误,请联系管理员处理。错误原因为:" e);
        return RespGenerator.fail(BaseCodeEnum.INTERNAL_SERVER_ERROR);
    }
}

自定义异常

BaseException

代码语言:javascript复制
public class BaseException extends RuntimeException{
    private String code;
    private String message;

    public BaseException(){
        super();
    }
    public BaseException(BaseCodeEnum baseCodeEnum){
        super(baseCodeEnum.getCode());
        this.code = baseCodeEnum.getCode();
        this.message = baseCodeEnum.getMessage();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

IllegalStateException

代码语言:javascript复制
public class IllegalStateException extends RuntimeException{
    public IllegalStateException() {
        super();
    }
    public IllegalStateException(String s) {
        super(s);
    }
}

NullPointerException

代码语言:javascript复制
public class NullPointerException extends RuntimeException {
    private static final long seriaVersionUID = 5162710183389028792L;

    public NullPointerException() {
        super();
    }
    public NullPointerException(String s) {
        super(s);
    }
}

0 人点赞