/* | |
* Copyright 1999-2011 Alibaba Group. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package com.alibaba.dubbo.rpc.filter; | |
import java.lang.reflect.Method; | |
import com.alibaba.dubbo.common.Extension; | |
import com.alibaba.dubbo.common.logger.Logger; | |
import com.alibaba.dubbo.common.logger.LoggerFactory; | |
import com.alibaba.dubbo.common.utils.ReflectUtils; | |
import com.alibaba.dubbo.common.utils.StringUtils; | |
import com.alibaba.dubbo.rpc.Filter; | |
import com.alibaba.dubbo.rpc.Invoker; | |
import com.alibaba.dubbo.rpc.RpcException; | |
import com.alibaba.dubbo.rpc.Invocation; | |
import com.alibaba.dubbo.rpc.Result; | |
import com.alibaba.dubbo.rpc.RpcResult; | |
import com.alibaba.dubbo.rpc.service.GenericService; | |
/** | |
* ExceptionInvokerFilter | |
* | |
* @author william.liangf | |
*/ | |
@Extension("exception") | |
public class ExceptionFilter implements Filter { | |
private static final Logger logger = LoggerFactory.getLogger(ExceptionFilter.class); | |
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { | |
Result result = invoker.invoke(invocation); | |
if (result.hasException() && GenericService.class != invoker.getInterface()) { | |
try { | |
Throwable exception = result.getException(); | |
try { | |
Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); | |
Class<?>[] exceptionClassses = method.getExceptionTypes(); | |
for (Class<?> exceptionClass : exceptionClassses) { | |
if (exception.getClass().equals(exceptionClass)) { | |
return result; | |
} | |
} | |
} catch (NoSuchMethodException e) { | |
return result; | |
} | |
//在package里有类,直接抛出 | |
String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); | |
String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); | |
if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)){ | |
return result; | |
} | |
//除上面二种情况外,server端打印日志,并包装成runtimeException抛给客户端 | |
logger.error("Got unchecked and undeclare service method invoke exception: " + exception.getMessage(), exception); | |
return new RpcResult(new RuntimeException(StringUtils.toString(exception))); | |
} catch (Throwable e) { | |
logger.warn(e.getMessage(), e); | |
return result; | |
} | |
} | |
return result; | |
} | |
} |