net.gdface.web.DefaultResponse Maven / Gradle / Ivy
package net.gdface.web;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* {@link Response}默认实现
* @author guyadong
*
*/
public class DefaultResponse implements Response{
private static boolean outStrackTrace = false;
/** 调用成功标志 */
private boolean success;
/** 调用的返回值 */
private Object result;
/** 异常信息 */
@JsonInclude(Include.NON_NULL)
private String errorMessage;
/** 异常堆栈信息 */
@JsonInclude(Include.NON_NULL)
private String stackTrace;
/** 代理对象 */
@JsonIgnore
private Object delegate;
/** 调用异常 */
@JsonIgnore
private Exception error;
@Override
public void onComplete(Object result) {
this.success = true;
this.result = result;
this.errorMessage = null;
this.stackTrace = null;
}
@Override
public void onComplete() {
onComplete(null);
}
@Override
public void onError(Exception e) {
if(e instanceof TranformValueException){
onComplete((((TranformValueException)e).getResult()));
return ;
}
success = false;
result = null;
errorMessage = e.getMessage();
error = e;
if(errorMessage == null){
errorMessage = e.getClass().getSimpleName();
}
if(outStrackTrace){
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
stackTrace = writer.toString();
}
}
@Override
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@Override
public Object getResult() {
return result;
}
@Override
public void setResult(Object result) {
this.result = result;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getStackTrace() {
return stackTrace;
}
public void setStackTrace(String stackTrace) {
this.stackTrace = stackTrace;
}
@Override
public Object delegate() {
return delegate;
}
@Override
public Exception error() {
return error;
}
@Override
public void delegate(Object delegate) {
this.delegate = delegate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DefaultResponse [success=");
builder.append(success);
builder.append(", ");
if (result != null) {
builder.append("result=");
builder.append(result);
builder.append(", ");
}
if (errorMessage != null) {
builder.append("errorMessage=");
builder.append(errorMessage);
builder.append(", ");
}
if (stackTrace != null) {
builder.append("stackTrace=");
builder.append(stackTrace);
}
builder.append("]");
return builder.toString();
}
/**
* 开启输出堆栈信息(默认为不开启)
* 开发时为了调试需要获取详细的异常堆栈信息可以开启
*/
public static void enableStrackTrace() {
outStrackTrace = true;
}
}