springboot返回数据及统一异常处理

在项目中,一般会对数据返回格式做一个统一的要求包括遇到的各种各样业务异常

1.定义返回的数据格式

package com.lhr.springbootlearning.VO;

import lombok.Data;

import java.io.Serializable;

/**
 * Created by lhr
 * 2018/10/22 20:33
 */

@Data
public class ResultVO<T> implements Serializable {

    private static final long serialVersionUID = 3068837394742385883L;

    /**
     * 错误信息.
     */
    private String msg;

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

    /**
     * 返回具体内容.
     */
    private T data;
}

 2.定义返回数据的方法

package com.lhr.springbootlearning.utils;

import com.lhr.springbootlearning.VO.ResultVO;

/**
 * Created by lhr
 * 2018/10/22 21:28
 */
public class ResultVOUtil {

    public static ResultVO success(Object object) {
        ResultVO resultVO = new ResultVO();
        resultVO.setMsg("success");
        resultVO.setCode(0);
        resultVO.setData(object);
        return resultVO;
    }

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

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

3.定义异常信息的枚举 

package com.lhr.springbootlearning.enums;

import lombok.Getter;

/**
 * Created by lhr
 * 2018/10/24 15:50
 */

@Getter
public enum ResultEnum {

    SUCCESS(0, "成功"),

    PARAM_ERROR(1, "参数不正确"),

    PRODUCT_NOT_EXIST(10, "商品不存在"),

    PRODUCT_STOCK_ERROR(11, "商品库存不正确"),
    ;

    private Integer code;

    private String message;

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

4.封装自定义异常

package com.lhr.springbootlearning.exception;

import com.lhr.springbootlearning.enums.ResultEnum;
import lombok.Getter;

/**
 * Created by lhr
 * 2018/10/24 15:08
 */
@Getter
public class SellException extends RuntimeException {

    private Integer code;

    public SellException(ResultEnum resultEnum) {
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }

    public SellException(Integer code, String message) {
        super(message);
        this.code = code;
    }
}

5.全局异常处理 

package com.lhr.springbootlearning.exception;

import com.lhr.springbootlearning.VO.ResultVO;
import com.lhr.springbootlearning.utils.ResultVOUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常
 * Created by lhr
 * 2018/10/31 17:19
 */

@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = SellException.class)
    @ResponseBody
    public ResultVO handlerException(SellException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }
}

 

注: 

@ControllerAdvice:定义统一的异常处理类

@ExceptionHandler:异常处理器,当出现其定义的异常时进行处理的方法,可传入多个需要捕获的异常类

使用:

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Validated OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);

        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车不能为空");
            throw new SellException(ResultEnum.CART_EMPTY);
        }

        OrderDTO createOrder = orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", createOrder.getOrderId());
        return ResultVOUtil.success(map);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值