dubbo服务中为了对外隐藏具体异常,给上游调用方更直接的返回提示,可以通过dubbo的Filter方式和SpringAop方式
dubbo的Filter方式如下:
1、实现过滤器
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
/**
* dubbo 对外异常统一处理
*
* @author awen
*/
@Activate(group = Constants.PROVIDER)
public class ExceptionFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Result result = null;
try {
result = invoker.invoke(invocation);
Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
Class returnType = method.getReturnType();
if (result.hasException()) {
Throwable throwable = result.getException();
if (returnType.getName().equals("com.liwen.domain.Result")) {
com.liwen.domain.Result myResult;
if (throwable instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) {
myResult = ResultUtils.wrapFailure(0, "重复操作");
} else {
myResult = ResultUtils.wrapFailure(1, "系统错误");
}
logger.error("服务异常 myResult=" + myResult, result);
return new RpcResult(myResult);
}
}
} catch (Exception e) {
logger.error("统一捕捉异常失败", e);
}
return result;
}
}
2、在resources目录下添加纯文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter,内容如下:
exceptionFilter=com.liwen.filter.ExceptionFilter
3、修改dubbo的provider配置文件,在dubbo:provider中添加配置的filter,如下:
<dubbo:provider filter="exceptionFilter"></dubbo:provider>