优雅的向前端返回封装数据

2019-03-01  本文已影响0人  riskker

自定义全局异常类

自定义一个异常继承RuntimeException,运行时异常不需要捕获,并且可以在业务层面主动抛出异常,异常抛出是被自定义的异常处理器捕获

public class BizException extends RuntimeException{

    /**
     * 业务错误码
     */
    private Integer code;

    /**
     * 业务错误说明
     */
    private String codeDesc;

    public BizException() {
        super();
        this.code = ResCode.BIZ_COMMON_ERROR.getCode();
        this.codeDesc = ResCode.BIZ_COMMON_ERROR.getCodeDesc();
    }

    public BizException(String codeDesc) {
        super();
        this.code = ResCode.BIZ_COMMON_ERROR.getCode();
        this.codeDesc = codeDesc;
    }

    public BizException(ResCode code) {
        super(code.getCodeDesc());
        this.code = code.getCode();
        this.codeDesc = code.getCodeDesc();
    }

错误码枚举

public enum ResCode {

    // 成功
    SUCC(0, ""),

    // token无效
    SYSTEM_AUTH_INVAD_ERROR(22, "token无效"),

    // token过期
    SYSTEM_AUTH_EXPIRE_ERROR(23, "token过期");
  
   private Integer code;

    private String codeDesc;

    ResCode(Integer code, String codeDesc) {
        this.code = code;
        this.codeDesc = codeDesc;
    }

    /**
     * 获取code字符串
     *
     * @return
     */
    public Integer getCode() {
        return code;
    }

    public String getCodeDesc() {
        return codeDesc;
    }

结果集:

public class ResObject {

    private Integer statusCode;
    private String resultDesc;
    private String message;
    private Object result;

    public ResObject(Integer statusCode, String codeDesc, Object data) {
        this.statusCode = statusCode;
        this.resultDesc = codeDesc;
        this.message = codeDesc;
        this.result = data;
    }

    public static ResObject build(ResCode resCode, Object data) {
        return new ResObject(resCode.getCode(), resCode.getCodeDesc(), data);
    }

自定义异常处理器

抛到控制层的异常被捕获,直接返回前端,非自己捕获的异常,统一定义为系统异常。

public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ex.printStackTrace();
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        Integer code = ResCode.SYSTEM_EEROR.getCode();
        String codeDesc = ResCode.SYSTEM_EEROR.getCodeDesc();
        if (ex instanceof BizException) {
            code = ((BizException) ex).getCode();
            codeDesc = ((BizException) ex).getCodeDesc();
        }
        mav.addObject("statusCode", code);
        mav.addObject("resultDesc", codeDesc);
        mav.addObject("message", codeDesc);
        return mav;
    }

}

控制器处理

所有的控制器继承父类,父类封装几个公共的方法
demo
   public ResObject succ(Object resultData) {
        return ResObject.build(ResCode.SUCC, resultData);
    }
上一篇下一篇

猜你喜欢

热点阅读