spring cloud 返回结果的封装

spring cloud 返回结果的封装

1.准备工作

/**
 *
 * @author xwq
 * @create 2019-07-30 9:46
 **/
public class ResponseStatusCode {


    /**
     * OK
     */
    public static final int OK = 0;

    /**
     * 未知异常
     */
    public static final int UNKNOW_EXCEPTION = 100;

    /**
     * 空指针异常异常
     */
    public static final int NULL_EXCEPTION = 101;

    /**
     * 参数异常
     */
    public static final int ARGUMENT_EXCEPTION = 104;

    /**
     * 自定义异常
     */
    public static final int SQL_EXCEPTION = 102;
}

2.返回的实体类

package com.bbg.domainManager.common.response;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 00309:42
 */

import java.io.Serializable;

/**
 *
 * @author xwq
 * @create 2019-07-30 9:42
 **/
public class ResponseResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int status; //状态码,根据服务实际需求自定义

    private String msg;

    private T data;

    private String url; //请求的url

    private Long host; //出现问题的根服务

    private String token;//令牌

    private String code;//校验码


    //-------------------成功
    public static ResponseResult ok(Object data, String url) {
        return new ResponseResult(ResponseStatusCode.OK, data, url, null);
    }

    public static ResponseResult ok(Object data) {
        return new ResponseResult(ResponseStatusCode.OK, data, null, null);
    }

    public static ResponseResult ok() {
        return new ResponseResult(ResponseStatusCode.OK, "操作成功", null, null);
    }

    public static ResponseResult ok(String msg, String url) {
        return new ResponseResult(ResponseStatusCode.OK, msg, null, url, null);
    }

    //-----------失败
    public static ResponseResult fail(int status, String msg, String url, Long host) {
        return new ResponseResult(status, msg, url, host);
    }

    public static ResponseResult fail(int status, String msg, String url) {
        return new ResponseResult(status, msg, url);
    }

    public static ResponseResult fail(int status, String msg) {
        return new ResponseResult(status, msg);
    }

    public ResponseResult() {

    }

    public ResponseResult(int status) {
        this.status = status;
    }

    public ResponseResult(int status, String msg, T data, String url, Long host) {
        this.status = status;
        this.msg = msg;
        this.data = data;
        this.url = url;
        this.host = host;
    }

    public ResponseResult(int status,String msg) {
        this.status = status;
        this.msg = msg;

    }

    public ResponseResult(int status,String msg,T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ResponseResult(String msg, T data, String url, Long host) {
        this.msg = msg;
        this.data = data;
        this.url = url;
        this.host = host;
    }

    public ResponseResult(int status, String msg, String url, Long host) {
        this.status = status;
        this.msg = msg;
        this.url = url;
        this.host = host;
    }

    public ResponseResult(int status, T data, String url, Long host) {
        this.status = status;
        this.data = data;
        this.url = url;
        this.host = host;
    }


    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    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;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getCode() {
        return code;
    }

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

3.异常处理

package com.bbg.domainManager.common.response;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:06
 */

import com.bbg.domainManager.common.response.exception.*;

/**
 *
 * @author xwq
 * @create 2019-07-30 10:06
 **/
public class ResponseHandler<T>  {



    /**
     * 处理调用远程接口的返回
     * @param responseResult
     * @return
     */
    public T handler(ResponseResult<?> responseResult) {
        int statusToken = responseResult.getStatus();
        String msg = responseResult.getMsg();
        Long host = responseResult.getHost();
        if (ResponseStatusCode.OK != statusToken){
            exceptionHandler(statusToken,msg, host);
        }

        return (T) responseResult.getData();
    }

    /**
     * 处理异常
     * @param statusToken 状态码
     * @param msg 错误消息
     * @param host 主机
     */
    private static void exceptionHandler(int statusToken, String msg, Long host) {
        if (ResponseStatusCode.ARGUMENT_EXCEPTION== statusToken) {
            throw new ArgumentException(msg, host);
        }else if (ResponseStatusCode.NULL_EXCEPTION== statusToken) {
            throw new CustomNullPointerException(msg, host);
        }  else if (ResponseStatusCode.UNKNOW_EXCEPTION== statusToken) {
            throw new UnknowException(msg, host);
        }else if (ResponseStatusCode.SQL_EXCEPTION== statusToken) {
            throw new CustomSQLException(msg, host);
        } else {
            throw new CustomException(statusToken, msg, host);
        }
    }

}

4.封装异常

package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:04
 */

import com.bbg.domainManager.common.response.ResponseResult;
import com.bbg.domainManager.common.response.ResponseStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.InetAddress;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 *
 * @author xwq
 * @create 2019-07-30 10:04
 **/
@RestControllerAdvice
public class ExceptionAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 出错服务端口
     */
    @Value("${server.port}")
    private int servicePort;

    /**
     * 封装异常
     *
     * @param req 请求
     * @param e   异常类
     * @return 返回封装类
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseResult jsonErrorHandler(HttpServletRequest req, Exception e) {
        logger.error(req.getRequestURL().toString(), e);
        Long host = null;
        //分配异常码与host
        int status = ResponseStatusCode.UNKNOW_EXCEPTION;
        String msg = e.getMessage();
        if (e instanceof NullPointerException || e instanceof CustomNullPointerException) {
            status = ResponseStatusCode.NULL_EXCEPTION;
            if (e instanceof CustomNullPointerException){
                host = ((CustomNullPointerException) e).getHost();
            }
        }  else if (e instanceof CustomException) {
            status = ((CustomException) e).getStatus();
            if (((CustomException) e).getHost() != null && !((CustomException) e).getHost().equals(0)){
                host = ((CustomException) e).getHost();
            }
        } else if (e instanceof SQLException || e instanceof CustomSQLException) {
            status = ResponseStatusCode.SQL_EXCEPTION;
            if (e instanceof CustomSQLException){
                host = ((CustomSQLException) e).getHost();
            }
        }else if (e instanceof UndeclaredThrowableException) {
            Throwable targetEx = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            if (targetEx != null) {
                msg = targetEx.getMessage();
            }
        }
        //获取出错服务ip
        int ip = 0;
        try {
            ip = Integer.valueOf(
                    Arrays.stream(
                            InetAddress.getLocalHost().getHostAddress()
                                    .split("\\.")).collect(Collectors.joining()));
        } catch (Exception e1) {
        }
        return ResponseResult.fail(
                status, msg, req.getRequestURL().toString(),
                host == null? Long.valueOf(String.valueOf(ip) + servicePort): host);
    }
}



5.一些想处理的异常

package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:02
 */

/**
 *
 * @author xwq
 * @create 2019-07-30 10:02
 **/
public class ArgumentException extends RuntimeException{

    public static final long serialVersionUID = 1L;
    private int status;
    private Long host;

    public ArgumentException(int status) {
        this.status = status;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     */
    public ArgumentException(int status, String message) {
        super(message);
        this.status = status;
    }

    public ArgumentException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    public ArgumentException(Throwable cause, int status) {
        super(cause);
        this.status = status;
    }

    public ArgumentException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
    }

    public ArgumentException(int status, Long host) {
        this.status = status;
        this.host = host;
    }

    public ArgumentException(String message, Long host) {
        super(message);
        this.host = host;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     * @param host 主机
     */
    public ArgumentException(int status, String message, Long host) {
        super(message);
        this.status = status;
        this.host = host;
    }

    public ArgumentException(String message, Throwable cause, int status, Long host) {
        super(message, cause);
        this.status = status;
        this.host = host;
    }

    public ArgumentException(Throwable cause, int status, Long host) {
        super(cause);
        this.status = status;
        this.host = host;
    }

    public ArgumentException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status, Long host) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
        this.host = host;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

}
package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:02
 */

/**
 *
 * @author xwq
 * @create 2019-07-30 10:02
 **/
public class CustomException extends RuntimeException{

    public static final long serialVersionUID = 1L;
    private int status;
    private Long host;

    public CustomException(int status) {
        this.status = status;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     */
    public CustomException(int status, String message) {
        super(message);
        this.status = status;
    }

    public CustomException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    public CustomException(Throwable cause, int status) {
        super(cause);
        this.status = status;
    }

    public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
    }

    public CustomException(int status, Long host) {
        this.status = status;
        this.host = host;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     * @param host 主机
     */
    public CustomException(int status, String message, Long host) {
        super(message);
        this.status = status;
        this.host = host;
    }

    public CustomException(String message, Throwable cause, int status, Long host) {
        super(message, cause);
        this.status = status;
        this.host = host;
    }

    public CustomException(Throwable cause, int status, Long host) {
        super(cause);
        this.status = status;
        this.host = host;
    }

    public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status, Long host) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
        this.host = host;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

}
package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:02
 */

/**
 *
 * @author xwq
 * @create 2019-07-30 10:02
 **/
public class CustomNullPointerException extends RuntimeException{

    public static final long serialVersionUID = 1L;
    private int status;
    private Long host;

    public CustomNullPointerException(int status) {
        this.status = status;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     */
    public CustomNullPointerException(int status, String message) {
        super(message);
        this.status = status;
    }

    public CustomNullPointerException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    public CustomNullPointerException(Throwable cause, int status) {
        super(cause);
        this.status = status;
    }

    public CustomNullPointerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
    }

    public CustomNullPointerException(int status, Long host) {
        this.status = status;
        this.host = host;
    }

    public CustomNullPointerException(String message, Long host) {
        super(message);
        this.host = host;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     * @param host 主机
     */
    public CustomNullPointerException(int status, String message, Long host) {
        super(message);
        this.status = status;
        this.host = host;
    }

    public CustomNullPointerException(String message, Throwable cause, int status, Long host) {
        super(message, cause);
        this.status = status;
        this.host = host;
    }

    public CustomNullPointerException(Throwable cause, int status, Long host) {
        super(cause);
        this.status = status;
        this.host = host;
    }

    public CustomNullPointerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status, Long host) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
        this.host = host;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

}
package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:02
 */

/**
 *
 * @author xwq
 * @create 2019-07-30 10:02
 **/
public class CustomSQLException extends RuntimeException{

    public static final long serialVersionUID = 1L;
    private int status;
    private Long host;

    public CustomSQLException(int status) {
        this.status = status;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     */
    public CustomSQLException(int status, String message) {
        super(message);
        this.status = status;
    }

    public CustomSQLException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    public CustomSQLException(Throwable cause, int status) {
        super(cause);
        this.status = status;
    }

    public CustomSQLException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
    }

    public CustomSQLException(int status, Long host) {
        this.status = status;
        this.host = host;
    }

    public CustomSQLException(String message, Long host) {
        super(message);
        this.host = host;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     * @param host 主机
     */
    public CustomSQLException(int status, String message, Long host) {
        super(message);
        this.status = status;
        this.host = host;
    }

    public CustomSQLException(String message, Throwable cause, int status, Long host) {
        super(message, cause);
        this.status = status;
        this.host = host;
    }

    public CustomSQLException(Throwable cause, int status, Long host) {
        super(cause);
        this.status = status;
        this.host = host;
    }

    public CustomSQLException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status, Long host) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
        this.host = host;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

}

package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:02
 */

/**
 *
 * @author xwq
 * @create 2019-07-30 10:02
 **/
public class UnknowException extends RuntimeException{

    public static final long serialVersionUID = 1L;
    private int status;
    private Long host;

    public UnknowException(int status) {
        this.status = status;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     */
    public UnknowException(int status, String message) {
        super(message);
        this.status = status;
    }

    public UnknowException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    public UnknowException(String message, Long host) {
        super(message);
        this.host = host;
    }

    public UnknowException(Throwable cause, int status) {
        super(cause);
        this.status = status;
    }

    public UnknowException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
    }

    public UnknowException(int status, Long host) {
        this.status = status;
        this.host = host;
    }

    /**
     * 抛出异常使用自定义的异常码
     * @param status 自定义异常码
     * @param message 异常信息
     * @param host 主机
     */
    public UnknowException(int status, String message, Long host) {
        super(message);
        this.status = status;
        this.host = host;
    }

    public UnknowException(String message, Throwable cause, int status, Long host) {
        super(message, cause);
        this.status = status;
        this.host = host;
    }

    public UnknowException(Throwable cause, int status, Long host) {
        super(cause);
        this.status = status;
        this.host = host;
    }

    public UnknowException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int status, Long host) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.status = status;
        this.host = host;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Long getHost() {
        return host;
    }

    public void setHost(Long host) {
        this.host = host;
    }

}

6.封装

package com.bbg.domainManager.common.response.exception;    /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author xwq
 * @date 2019/7/30 003010:03
 */

import com.bbg.domainManager.common.response.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *
 * @author xwq
 * @create 2019-07-30 10:03
 **/
@ControllerAdvice
public class CustomResponseAdivce implements ResponseBodyAdvice<Object> {

    // 这个方法表示对于哪些请求要执行beforeBodyWrite,返回true执行,返回false不执行
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    // 对于返回的对象如果不是最终对象ResponseResult,则选包装一下
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) serverHttpRequest;
        String url = servletServerHttpRequest.getServletRequest().getRequestURL().toString();

        if (!(o instanceof ResponseResult)) {
            ResponseResult responseResult = null;
            // 因为handler处理类的返回类型是String,为了保证一致性,这里需要将ResponseResult转回去
            if (o instanceof String) {
                responseResult = ResponseResult.ok(o, url);
                ObjectMapper mapper = new ObjectMapper();
                String responseString = "";
                try {
                    responseString = mapper.writeValueAsString(responseResult);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return responseString;
            }else {
                responseResult = ResponseResult.ok(o, url);
                return responseResult;
            }
        }
        return o;
    }

}

使用

/**
	 * 新增
	 *
	 */
	@RequestMapping(value="/addDomain", method = {RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	@ApiOperation(value="域管理新增",notes="")
	public ResponseResult addDomain(HttpServletRequest request) {
		DomainDto domainDto = new DomainDto();
		String key = request.getParameter("key");
		if(StrUtil.isEmpty(key)){

			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域key不能为空");
		}else if(key.length() > 40){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域key不能超过40字");

		}

		String name = request.getParameter("name");
		if(StrUtil.isEmpty(name)){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域名称不能为空");

		}else if(name.length() > 40){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域名称不能超过40字");
		}

		String desc = request.getParameter("desc");
		if(!StrUtil.isEmpty(desc) && desc.length()>100){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域描述不能超过100字");

		}

		String status = request.getParameter("status");
		if(StrUtil.isEmpty(status)){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域状态不能为空");

		}else if(status.length() > 2){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域状态不能超过2字");

		}

		String creater = request.getParameter("creater");//创建人

		String fatherkey = request.getParameter("fatherkey");

		domainDto.setKey(key);
		domainDto.setName(name);
		domainDto.setDesc(desc);
		domainDto.setStatus(status);
		domainDto.setFatherkey(fatherkey);
		domainDto.setCreater(creater);
		domainDto.setCreateTime(new Date());
		domainDto.setLastmodifyTime(new Date());


		//第一步,去判断key,看看是否重复,不需要去考虑状态
		DomainDto dto = new DomainDto();
		dto.setKey(key);
		dto = domainService.findBy(dto);
		if(dto != null){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域key不能重复");

		}

		//第二步,去判断name,看看是否重复,不需要去考虑状态
		DomainDto dto1 = new DomainDto();
		dto1.setName(name);
		dto1 = domainService.findBy(dto1);
		if(dto1 != null){
			return ResponseResult.fail(ResponseStatusCode.ARGUMENT_EXCEPTION, "域名称不能重复");

		}

		domainService.addDomain(domainDto);

		return ResponseResult.ok(domainDto);
	}
	```
	

你可能感兴趣的:(步步高,spring,cloud)