All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sinszm.common.Response Maven / Gradle / Ivy

Go to download

基于SpringBoot扩展生态应用公共组件 Copyright © 2020 智慧程序猿 All rights reserved. https://www.sinsz.com

There is a newer version: 1.1.3.RELEASE
Show newest version
package com.sinszm.common;

import com.sinszm.common.exception.ApiError;
import com.sinszm.common.exception.SystemApiError;
import org.nutz.json.Json;

/**
 * 统一返回值对象
 *
 * @author chenjianbo
 */
public class Response {

    private static final String MESSAGE = "SUCCESS";

    /**
     * 状态
     */
    private Boolean state;

    /**
     * 请求消息内容
     */
    private String message;

    /**
     * 返回值对象
     */
    private T body;

    /**
     * 异常栈
     */
    private Throwable cause;

    private Response() {
    }

    public Boolean getState() {
        return state;
    }

    private void setState(Boolean state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

    private void setMessage(String message) {
        this.message = message;
    }

    public T getBody() {
        return body;
    }

    private void setBody(T body) {
        this.body = body;
    }

    public Throwable getCause() {
        return cause;
    }

    private void setCause(Throwable cause) {
        this.cause = cause;
    }

    /**
     * 成功返回
     * @param body  返回值
     * @param    类型
     * @return      响应
     */
    public synchronized static  Response success(T body) {
        Response response = new Response<>();
        response.setState(true);
        response.setMessage(MESSAGE);
        if (body != null) {
            response.setBody(body);
        }
        response.setCause(null);
        return response;
    }

    /**
     * 失败返回
     * @param apiError  错误代码
     * @param cause     异常栈
     * @return          响应
     */
    public synchronized static Response fail(ApiError apiError, Throwable cause) {
        Response response = new Response<>();
        response.setState(false);
        response.setMessage(
                apiError.message() == null ? SystemApiError.SYSTEM_ERROR_01.message() : apiError.message()
        );
        response.setCause(cause);
        response.setBody(null);
        return response;
    }

    /**
     * 自定义失败信息组装
     * @param body  数据
     * @param msg   消息
     * @param    泛型定义
     * @return      响应
     */
    public synchronized static  Response fail(T body, String msg) {
        Response response = new Response<>();
        response.setState(false);
        response.setMessage(msg == null ? SystemApiError.SYSTEM_ERROR_01.message() : msg);
        response.setCause(null);
        response.setBody(body);
        return response;
    }

    @Override
    public String toString() {
        return Json.toJson(this);
    }
}