栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot通用返回处理总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot通用返回处理总结

IntelliJ IDEA 2021.2.2
JDK 1.8.0
SpringBoot 2.6.2

通用返回处理

简单来说是返回给前端的对应返回值(成功or失败),让前端明确的知晓对应的正确or报错信息。

代码 CommonRes类

此类定义通用对象的处理。

package com.gzh.dianping.common;
public class CommonRes {
    //表明对应请求的返回处理结果, "success"或"fail"
    private String status;
    //若status=success,表明返回对应的json类数据
    //若status=fail,则data内将使用通用的错误码对应的格式
    private Object data;
    //定义一个通用的创建返回对象的方法
    public static CommonRes create(Object result){
        return CommonRes.create(result, "success");
    }
    public static CommonRes create(Object result, String status){
         CommonRes commonRes = new CommonRes();
         commonRes.setStatus(status);
         commonRes.setData(result);
         return commonRes;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public Object getData() {
        return data;
    }

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

CommonError类

此类定义通用的返回对象的错误处理的方式。

package com.gzh.dianping.common;

public class CommonError {
	//错误码
    private Integer errCode;
	//错误信息
    private String errMsg;

    public CommonError(Integer errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }
    //企业级的方式:错误穷举
    public CommonError(EmBusinessError emBusinessError){
        this.errCode = emBusinessError.getErrCode();
        this.errMsg = emBusinessError.getErrMsg();
    }
    public Integer getErrCode() {
        return errCode;
    }

    public void setErrCode(Integer errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
}

企业级方式:错误枚举

通过枚举类预先定义的错误往CommonError里赋值(与上一个类里的第二个构造函数组装)。

package com.gzh.dianping.common;

public enum EmBusinessError {

    NO_OBJECT_FOUND(10001, "请求对象不存在"),
    UNKNOWN_ERROR(10002, "未知错误"),
    NO_HANDLER_FOUND(10003, "找不到执行的路径操作"),
    BIND_EXCEPTION_ERROR(10004,"请求参数错误");
	//与CommonError对应
    private Integer errCode;
    private String errMsg;

    public Integer getErrCode() {
        return errCode;
    }

    public void setErrCode(Integer errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    EmBusinessError(Integer errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }
}

通用异常处理机制处理代码冗余:java的魅力之处在于抛出异常之后的处理
package com.gzh.dianping.common;

public class BusinessException extends Exception{
    private CommonError commonError;
    public BusinessException(EmBusinessError emBusinessError){
        super();//创建自己的异常
        this.commonError = new CommonError(emBusinessError);
    }
        public CommonError getCommonError() {
        return commonError;
    }
}

通用异常处理拦截器:AOP思想
package com.gzh.dianping.common;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Handler;

@ControllerAdvice
public class GlobalExceptionHandler {

	//只要对应的controller抛出异常,都来这里统一处理。(即controller往上抛,会被这个方法拦截)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception ex){
        if(ex instanceof BusinessException){
            return CommonRes.create(((BusinessException)ex).getCommonError(), "fail");
        }else if(ex instanceof NoHandlerFoundException){
            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLER_FOUND);
            return CommonRes.create(commonError, "fail");
        }else if(ex instanceof ServletRequestBindingException){
            CommonError commonError = new CommonError(EmBusinessError.BIND_EXCEPTION_ERROR);
            return CommonRes.create(commonError, "fail");
        }else
        {
            CommonError commonError = new CommonError(EmBusinessError.UNKNOWN_ERROR);
            return CommonRes.create(commonError, "fail");
        }

    }
}

Controller
    @RequestMapping("/get")
    @ResponseBody
    public CommonRes getUser(@RequestParam(name="id")Integer id) throws BusinessException {
        User user =  userService.getUserById(id);
        if(user == null){
            throw new BusinessException(EmBusinessError.NO_OBJECT_FOUND);
        }else {
            return CommonRes.create(user);
        }
    }

总结

本文为自学梳理,细节可以共同讨论。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号