Springboot07配制数据统一返回格式以及定义统一的异常处理类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl18603543572/article/details/86010127

1、创建返回数据结构模型


/**
 * http请求返回的最外层对象
 */
public class Result<T> {

    /** 错误码. */
    private Integer code;

    /** 提示信息. */
    private String msg;

    /** 具体的内容. */
    private T data;

    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

2、创建 构造返回数据模型工具类


public class ResultUtil {

    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(1000);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }

    public static Result success() {
        return success(null);
    }

    public static Result error(Integer code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

3、在controller中使用数据模型


@RestController
@RequestMapping(value = "/users")
public class UserController  {


    @Autowired
    private UserRepository userRepository;


    /**
     * 用户登录
     * @param userModel
     * @return
     * @throws UserException
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result userLogin(UserModel userModel)throws UserException{

        Optional<UserModel> optional =userRepository.findOne(new Specification<UserModel>() {
            @Override
            public Predicate toPredicate(Root<UserModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"),userModel.getName()));
                return null;
            }
        });

        if (optional != null&&optional.isPresent()) {
            UserModel queryUserModel = optional.get();
            if (queryUserModel.getPassword().equals(userModel.getPassword())) {
                return ResultUtil.success();
            }else {
                return ResultUtil.error(1002,"帐户或密码错误");
            }

        }
        return ResultUtil.error(1003,"帐户或密码错误");

    }
}

在这里 我们声明的用户登录数据检验 请求要求为post ,当我们使用的get请求时,会被我们定义的全局异常捕捉到

@ControllerAdvice
class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    //@ExceptionHandler用来定义函数针对的异常类型
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {

        if (e instanceof UserException) {
            logger.error("用用户操作异常 {}", e.getMessage());
            return ResultUtil.error(1002, e.getMessage());
        }else {
            logger.error("【系统异常】{}", e);
            return ResultUtil.error(-1, "未知错误");
        }


    }

}

当请求方法为正确时,参数异常时,

正常访问

猜你喜欢

转载自blog.csdn.net/zl18603543572/article/details/86010127