springboot 统一异常处理;统一返回结果处理

        自己封装的一个springboot 接口框架,使用springboot+mybatis,开箱即用使用,互相交流。地址:https://gitee.com/xiaokd/springboot-demo

我项目中使用了lombok,请大家先配置好lombok插件

1. 定义一个父级枚举接口(所有异常枚举类实现此接口)

package com.lwk.springbootdemo.common.exception;

/**
 * 异常枚举父类接口
 * @description
 * @anthor lwk
 * @date 2022/4/17 16:59
 */
public interface SuperEnumFace {
    /**
     * 获取状态码
     * @return
     */
    public int getCode();

    /**
     * 获取响应消息
     * @return
     */
    public String getMessage();
}

2. 定义一个基本异常类 (注意自定义的异常类类要继承 RuntimeException,因为spring默认抛出运行时异常事务才会自动回滚)

package com.lwk.springbootdemo.common.exception;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 自定义基础异常
 * @description
 * @anthor lwk
 * @date 2022/4/17 16:50
 */
@Getter
@AllArgsConstructor
public class BaseException extends RuntimeException{
    private int code;
    private String message;

    /**
     * 自定义异常枚举构造
     * @param superEnumFace
     */
    public BaseException(SuperEnumFace superEnumFace){
        this.code = superEnumFace.getCode();
        this.message = superEnumFace.getMessage();
    }
}

3. 定义一个异常枚举

package com.lwk.springbootdemo.common.exception;

import lombok.AllArgsConstructor;

/**
 * 自定义基础异常枚举
 * @description
 * @anthor lwk
 * @date 2022/4/17 17:09
 */
@AllArgsConstructor
public enum BaseExceptionEnum implements SuperEnumFace{

    SUCESS(20000, "操作成功"),
    FAIL(40000, "操作失败"),
    ERROR(50000, "服务器异常,请稍后重试"),
    LOGIN_EXPIRE(60000, "登录状态过期,请重新登陆")
    ;

    private int code;
    private String message;

    @Override
    public int getCode() {
        return this.code;
    }

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

4. 定义一个结果类 

package com.lwk.springbootdemo.common.repo;

import com.lwk.springbootdemo.common.exception.BaseExceptionEnum;
import com.lwk.springbootdemo.common.exception.SuperEnumFace;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;

/**
 * 统一响应结果
 * @description
 * @anthor lwk
 * @date 2022/4/17 17:34
 */
@Data
@AllArgsConstructor
public class Result<T> implements Serializable {
    /**
     * 状态码
     */
    private int code;
    /**
     * 响应消息
     */
    private String message;
    /**
     * 响应数据
     */
    private T data;

    public Result(int code, String message){
        this.code = code;
        this.message = message;
    }

    public Result(SuperEnumFace superEnumFace){
        this.code = superEnumFace.getCode();
        this.message = superEnumFace.getMessage();
    }

    public Result(SuperEnumFace superEnumFace, T data){
        this.code = superEnumFace.getCode();
        this.message = superEnumFace.getMessage();
        this.data = data;
    }

    /**
     * 服务器错误
     * @param message
     * @return
     */
    public static Result error(String message){
        if(ObjectUtils.isEmpty(message)){
            return new Result(BaseExceptionEnum.ERROR);
        }else {
            return new Result(BaseExceptionEnum.ERROR.getCode(), message);
        }
    }

    /**
     *
     * @param data
     * @return
     */
    public static <T> Result success(T data){
        return new Result(BaseExceptionEnum.SUCESS, data);
    }
}

5. 定义统一异常处理类

package com.lwk.springbootdemo.common.advice;

import com.lwk.springbootdemo.common.exception.BaseException;
import com.lwk.springbootdemo.common.repo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 * @description
 * @anthor lwk
 * @date 2022/4/17 17:54
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    /**
     * 处理业务异常
     * @param baseException
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result exceptionHandler(BaseException baseException){
        log.error("业务异常:{}", baseException.getMessage());
        return Result.error(baseException.getMessage());
    }

    /**
     * 未知异常处理
     * @param exception
     * @return
     */
    public Result exceptionHandler(Exception exception){
        log.error("运行时异常:{}", exception.getMessage());
        return Result.error(null);
    }
}

6. 定义统一结果处理类(string类型要单独进行处理)

package com.lwk.springbootdemo.common.advice;

import com.alibaba.fastjson.JSON;
import com.lwk.springbootdemo.common.repo.Result;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回结果增强
 * @description
 * @anthor lwk
 * @date 2022/4/17 18:38
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.getGenericParameterType().equals(Result.class);
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(returnType.getGenericParameterType().equals(String.class)){ //返回string类型
            return JSON.toJSONString(Result.success(body));
        }else if(body == null){ //返回void
            return Result.success(null);
        }else {
            return Result.success(body);
        }
    }
}

7. 抛出异常,查看返回结果

package com.lwk.springbootdemo.service.impl;

import com.lwk.springbootdemo.common.exception.BaseException;
import com.lwk.springbootdemo.common.exception.BaseExceptionEnum;
import com.lwk.springbootdemo.entity.Dept;
import com.lwk.springbootdemo.mapper.DeptMapper;
import com.lwk.springbootdemo.service.DeptService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description
 * @anthor lwk
 * @date 2022/4/26 14:01
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Resource
    private DeptMapper deptMapper;

    @Override
    public List<Dept> getDepts(int id) {
        if(id == 0){
            throw new BaseException(BaseExceptionEnum.ERROR);
        }
        List<Dept> depts = deptMapper.getDetps();
        return depts;
    }
}

8. 结果显示:参数传1,正确返回数据;参数传0,抛出异常

 

9. 收工 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值