Dubbo全局异常处理,代码如下:
@ControllerAdvice
@Activate(group = {CommonConstants.PROVIDER})
public class AuthInfoProviderFilter implements Filter {
private static final String LOGIN_INTERFACE = "com.techhf.tenant.client.api.IAuthFeign";
private static final String LOGIN_METHOD = "login";
@SneakyThrows
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String serviceInterface = invoker.getUrl().getServiceInterface();
String methodName = invocation.getMethodName();
if (LOGIN_INTERFACE.equals(serviceInterface) && LOGIN_METHOD.equals(methodName)) {
return invoking(invoker, invocation);
} else {
String token = RpcContext.getServiceContext().getAttachment("token");
if (token == null) {
return AsyncRpcResult.newDefaultAsyncResult(R.failed("token不能为空"), invocation);
}
try {
AuthInfo authInfo = JSON.parseObject(token, AuthInfo.class);
AuthContextHolder.setAuthInfo(authInfo);
return invoking(invoker, invocation);
} finally {
AuthContextHolder.clear();
}
}
}
@SneakyThrows
public Result invoking(Invoker<?> invoker, Invocation invocation) throws RpcException {
Result result = invoker.invoke(invocation);
if (result.hasException()) {
ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(this.getClass());
Exception exception = (Exception) result.getException();
Method method = resolver.resolveMethod(exception);
Object obj = method.invoke(this, exception);
return AsyncRpcResult.newDefaultAsyncResult(obj, invocation);
}
return result;
}
@ExceptionHandler(value = BusinessServiceException.class)
public Object businessServiceException(BusinessServiceException e) {
return R.failed(e.getMessage());
}
}