com.alipay.sofa.rpc.core.exception.SofaRpcException Java Examples

The following examples show how to use com.alipay.sofa.rpc.core.exception.SofaRpcException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TripleClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public SofaResponse syncSend(SofaRequest request, int timeout) throws SofaRpcException {
    SofaResponse sofaResponse = null;
    SofaRpcException throwable = null;

    try {
        RpcInternalContext context = RpcInternalContext.getContext();

        beforeSend(context, request);

        RpcInvokeContext invokeContext = RpcInvokeContext.getContext();
        invokeContext.put(TripleContants.SOFA_REQUEST_KEY, request);
        invokeContext.put(TripleContants.SOFA_CONSUMER_CONFIG_KEY, transportConfig.getConsumerConfig());
        sofaResponse = tripleClientInvoker.invoke(request, timeout);
        return sofaResponse;
    } catch (Exception e) {
        throwable = convertToRpcException(e);
        throw throwable;
    } finally {
        if (EventBus.isEnable(ClientSyncReceiveEvent.class)) {
            EventBus.post(new ClientSyncReceiveEvent(transportConfig.getConsumerConfig(),
                    transportConfig.getProviderInfo(), request, sofaResponse, throwable));
        }
    }
}
 
Example #2
Source File: JacksonSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public Object decode(AbstractByteBuf data, Class clazz, Map<String, String> context) throws SofaRpcException {

    Object result = null;

    if (clazz == null) {
        throw buildDeserializeError("class is null!");
    } else {
        try {
            result = mapper.readValue(data.array(), clazz);
        } catch (IOException e) {
            throw buildDeserializeError(e.getMessage());
        }
    }

    return result;
}
 
Example #3
Source File: MsgPackSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected AbstractByteBuf encodeSofaResponse(SofaResponse sofaResponse, Map<String, String> context)
        throws SofaRpcException {
    AbstractByteBuf byteBuf;
    if (sofaResponse.isError()) {
        // 框架异常:错误则body序列化的是错误字符串
        byteBuf = encode(sofaResponse.getErrorMsg(), context);
    } else {
        // 正确返回则解析序列化的Msgpack返回对象
        Object appResponse = sofaResponse.getAppResponse();
        if (appResponse instanceof Throwable) {
            // 业务异常序列化的是错误字符串
            byteBuf = encode(((Throwable) appResponse).getMessage(), context);
        } else {
            byteBuf = encode(appResponse, context);
        }
    }
    return byteBuf;
}
 
Example #4
Source File: JacksonSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected AbstractByteBuf encodeSofaResponse(SofaResponse sofaResponse, Map<String, String> context)
    throws SofaRpcException {
    AbstractByteBuf byteBuf;
    if (sofaResponse.isError()) {
        // rpc exception:error when body is illegal string
        byteBuf = encode(sofaResponse.getErrorMsg(), context);
    } else {
        //ok: when json can be deserialize correctly.
        Object appResponse = sofaResponse.getAppResponse();
        if (appResponse instanceof Throwable) {
            // biz exception:error when body is illegal string
            byteBuf = encode(((Throwable) appResponse).getMessage(), context);
        } else {
            byteBuf = encode(appResponse, context);
        }
    }
    return byteBuf;
}
 
Example #5
Source File: JacksonSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractByteBuf encode(Object object, Map<String, String> context) throws SofaRpcException {
    if (object == null) {
        throw buildSerializeError("Unsupported null message!");
    } else if (object instanceof SofaRequest) {
        return encodeSofaRequest((SofaRequest) object, context);
    } else if (object instanceof SofaResponse) {
        return encodeSofaResponse((SofaResponse) object, context);
    } else {
        try {
            return new ByteArrayWrapperByteBuf(mapper.writeValueAsBytes(object));
        } catch (JsonProcessingException e) {
            throw buildSerializeError(e.getMessage());
        }
    }
}
 
Example #6
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractByteBuf encode(Object object, Map<String, String> context) throws SofaRpcException {
    if (object == null) {
        throw buildSerializeError("Unsupported null message!");
    } else if (object instanceof SofaRequest) {
        return encodeSofaRequest((SofaRequest) object, context);
    } else if (object instanceof SofaResponse) {
        return encodeSofaResponse((SofaResponse) object, context);
    } else {
        Class clazz = object.getClass();
        Schema schema = RuntimeSchema.getSchema(clazz);
        // Re-use (manage) this buffer to avoid allocating on every serialization
        LinkedBuffer buffer = LinkedBuffer.allocate(512);
        // ser
        try {
            return new ByteArrayWrapperByteBuf(ProtostuffIOUtil.toByteArray(object, schema, buffer));
        } finally {
            buffer.clear();
        }
    }
}
 
Example #7
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected AbstractByteBuf encodeSofaResponse(SofaResponse sofaResponse, Map<String, String> context)
    throws SofaRpcException {
    AbstractByteBuf byteBuf;
    if (sofaResponse.isError()) {
        // 框架异常:错误则body序列化的是错误字符串
        byteBuf = encode(sofaResponse.getErrorMsg(), context);
    } else {
        // 正确返回则解析序列化的protobuf返回对象
        Object appResponse = sofaResponse.getAppResponse();
        if (appResponse instanceof Throwable) {
            // 业务异常序列化的是错误字符串
            byteBuf = encode(((Throwable) appResponse).getMessage(), context);
        } else {
            byteBuf = encode(appResponse, context);
        }
    }
    return byteBuf;
}
 
Example #8
Source File: HystrixFilterAsyncTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testHystrixTimeout() {
    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000);

    HystrixService HystrixService = consumerConfig.refer();

    long start = System.currentTimeMillis();
    try {
        HystrixService.sayHello("abc", 24);
        Future future = SofaResponseFuture.getFuture();
        Assert.assertFalse(future.isDone());
        Assert.assertFalse(future.isCancelled());
        SofaResponseFuture.getResponse(10000, true);
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SofaRpcException);
        final Throwable cause = e.getCause();
        Assert.assertTrue(cause.getMessage(), cause instanceof HystrixRuntimeException);
        Assert.assertTrue((System.currentTimeMillis() - start) > HYSTRIX_DEFAULT_TIMEOUT);
    }
}
 
Example #9
Source File: RestClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected Object buildProxy(ClientTransportConfig transportConfig) throws SofaRpcException {
    SofaResteasyClientBuilder builder = new SofaResteasyClientBuilder();

    ResteasyClient client = builder
        .registerProvider().logProviders()
        .establishConnectionTimeout(transportConfig.getConnectTimeout(), TimeUnit.MILLISECONDS)
        .socketTimeout(transportConfig.getInvokeTimeout(), TimeUnit.MILLISECONDS)
        .connectionPoolSize(Math.max(transportConfig.getConnectionNum(), MIN_CONNECTION_POOL_SIZE))
        .build();

    ProviderInfo provider = transportConfig.getProviderInfo();
    String url = "http://" + provider.getHost() + ":" + provider.getPort()
        + StringUtils.CONTEXT_SEP + StringUtils.trimToEmpty(provider.getPath());
    ResteasyWebTarget target = client.target(url);
    return target.proxy(ClassUtils.forName(transportConfig.getConsumerConfig().getInterfaceId()));
}
 
Example #10
Source File: RestClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected Method getMethod(SofaRequest request) throws SofaRpcException {
    String serviceUniqueName = request.getTargetServiceUniqueName();
    String methodName = request.getMethodName();
    String[] methodSigns = request.getMethodArgSigs();

    Method method = ReflectCache.getOverloadMethodCache(serviceUniqueName, methodName, methodSigns);
    if (method == null) {
        try {
            String interfaceName = request.getInterfaceName();
            method = ClassUtils.forName(interfaceName)
                .getMethod(methodName, ClassTypeUtils.getClasses(methodSigns));
            ReflectCache.putOverloadMethodCache(serviceUniqueName, method);
        } catch (NoSuchMethodException e) {
            throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Method not found", e);
        }
    }
    return method;
}
 
Example #11
Source File: BoltSendableResponseCallback.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 发送响应数据
 *
 * @param response 响应
 * @param sofaException SofaRpcException
 */
protected void sendSofaResponse(SofaResponse response, SofaRpcException sofaException) {
    try {
        if (RpcInvokeContext.isBaggageEnable()) {
            BaggageResolver.carryWithResponse(RpcInvokeContext.peekContext(), response);
        }
        asyncContext.sendResponse(response);
    } finally {
        if (EventBus.isEnable(ServerSendEvent.class)) {
            EventBus.post(new ServerSendEvent(request, response, sofaException));
        }
        if (EventBus.isEnable(ServerEndHandleEvent.class)) {
            EventBus.post(new ServerEndHandleEvent());
        }
    }
}
 
Example #12
Source File: HttpTransportUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected static String[] getInterfaceIdAndMethod(String uri) {
    String[] result;
    int i = uri.indexOf('?');
    if (i > 0) {
        uri = uri.substring(0, i);
    }
    String[] end = uri.split("/");
    if (end.length < 3) {
        throw new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE,
            "The correct URI format is: http://ip:port/serviceName/methodName");
    }
    int resultLength = 2;
    result = new String[resultLength];
    //从第二个元素开始copy 第一个是空字符串
    System.arraycopy(end, 1, result, 0, resultLength);
    return result;
}
 
Example #13
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void oneWaySend(SofaRequest request, int timeout) throws SofaRpcException {
    checkConnection();
    RpcInternalContext context = RpcInternalContext.getContext();
    InvokeContext invokeContext = createInvokeContext(request);
    SofaRpcException throwable = null;
    try {
        beforeSend(context, request);
        doOneWay(request, invokeContext, timeout);
    } catch (Exception e) { // 其它异常
        throwable = convertToRpcException(e);
        throw throwable;
    } finally {
        afterSend(context, invokeContext, request);
        if (EventBus.isEnable(ClientSyncReceiveEvent.class)) {
            EventBus.post(new ClientSyncReceiveEvent(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), request, null, throwable));
        }
    }
}
 
Example #14
Source File: HttpTransportUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 根据序列化名称获得序列化类型
 *
 * @param serialization 序列化类型名称
 * @return 序列化编码
 */
public static byte getSerializeTypeByName(String serialization) throws SofaRpcException {
    String sz = serialization.toLowerCase();
    Byte code;
    if (RpcConstants.SERIALIZE_HESSIAN2.equals(sz) || RpcConstants.SERIALIZE_HESSIAN.equals(sz)) {
        code = SerializerFactory.getCodeByAlias(RpcConstants.SERIALIZE_HESSIAN2);
    } else {
        code = SerializerFactory.getCodeByAlias(serialization);
    }
    if (code != null) {
        return code;
    } else {
        throw new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE, LogCodes.getLog(
            LogCodes.ERROR_UNSUPPORTED_SERIALIZE_TYPE, serialization));
    }
}
 
Example #15
Source File: AbstractHttpClientHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected void decode(SofaResponse response) {
    AbstractByteBuf byteBuffer = response.getData();
    if (byteBuffer != null) {
        try {
            Map<String, String> context = new HashMap<String, String>(4);
            if (response.isError()) {
                context.put(RemotingConstants.HEAD_RESPONSE_ERROR, response.isError() + "");
                String errorMsg = StringSerializer.decode(byteBuffer.array());
                response.setAppResponse(new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, errorMsg));
            } else {
                context.put(RemotingConstants.HEAD_TARGET_SERVICE, request.getTargetServiceUniqueName());
                context.put(RemotingConstants.HEAD_METHOD_NAME, request.getMethodName());
                Serializer serializer = SerializerFactory.getSerializer(response.getSerializeType());
                serializer.decode(byteBuffer, response, context);
            }
        } finally {
            byteBuffer.release();
            response.setData(null);
        }
    }
}
 
Example #16
Source File: CustomEchoFilter2.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    LOGGER.info("echo2 request : {}, {}", request.getInterfaceName() + "." + request.getMethodName(),
        request.getMethodArgs());

    SofaResponse response = invoker.invoke(request);

    if (response == null) {
        return response;
    } else if (response.isError()) {
        LOGGER.info("server rpc error: {}", response.getErrorMsg());
    } else {
        Object ret = response.getAppResponse();
        if (ret instanceof Throwable) {
            LOGGER.error("server biz error: {}", (Throwable) ret);
        } else {
            LOGGER.info("echo2 response : {}", response.getAppResponse());
        }
    }

    return response;
}
 
Example #17
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseFuture asyncSend(SofaRequest request, int timeout) throws SofaRpcException {
    checkConnection();
    RpcInternalContext context = RpcInternalContext.getContext();
    InvokeContext boltInvokeContext = createInvokeContext(request);
    try {
        beforeSend(context, request);
        boltInvokeContext.put(RemotingConstants.INVOKE_CTX_RPC_CTX, context);
        return doInvokeAsync(request, context, boltInvokeContext, timeout);
    } catch (Exception e) {
        throw convertToRpcException(e);
    } finally {
        afterSend(context, boltInvokeContext, request);
    }
}
 
Example #18
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected AbstractByteBuf encodeSofaRequest(SofaRequest sofaRequest, Map<String, String> context)
    throws SofaRpcException {
    Object[] args = sofaRequest.getMethodArgs();
    if (args.length > 1) {
        throw buildSerializeError("Protobuf only support one parameter!");
    }
    return encode(args[0], context);
}
 
Example #19
Source File: BoltSendableResponseCallback.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * A->B(当前)->C的场景下,将远程服务端C的RPc异常异步返回给调用者A
 *
 * @see SofaResponseCallback#onSofaException(SofaRpcException, String, RequestBase)
 */
@Override
public void sendSofaException(SofaRpcException sofaException) {
    checkState();
    SofaResponse response = new SofaResponse();
    response.setErrorMsg(sofaException.getMessage());
    sendSofaResponse(response, sofaException);
}
 
Example #20
Source File: ClientProxyInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * proxy拦截的调用
 *
 * @param request 请求消息
 * @return 调用结果
 */
@Override
public SofaResponse invoke(SofaRequest request) throws SofaRpcException {
    SofaResponse response = null;
    Throwable throwable = null;
    try {
        RpcInternalContext.pushContext();
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setProviderSide(false);
        // 包装请求
        decorateRequest(request);
        try {
            // 产生开始调用事件
            if (EventBus.isEnable(ClientStartInvokeEvent.class)) {
                EventBus.post(new ClientStartInvokeEvent(request));
            }
            // 得到结果
            response = cluster.invoke(request);
        } catch (SofaRpcException e) {
            throwable = e;
            throw e;
        } finally {
            // 产生调用结束事件
            if (!request.isAsync()) {
                if (EventBus.isEnable(ClientEndInvokeEvent.class)) {
                    EventBus.post(new ClientEndInvokeEvent(request, response, throwable));
                }
            }
        }
        // 包装响应
        decorateResponse(response);
        return response;
    } finally {
        RpcInternalContext.removeContext();
        RpcInternalContext.popContext();
    }
}
 
Example #21
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void checkConnection() throws SofaRpcException {

        Connection connection = fetchConnection();
        if (connection == null) {
            throw new SofaRpcException(RpcErrorType.CLIENT_NETWORK, "connection is null");
        }
        if (!connection.isFine()) {
            throw new SofaRpcException(RpcErrorType.CLIENT_NETWORK, "connection is not fine");
        }
    }
 
Example #22
Source File: SentinelSofaRpcConsumerFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    // Now only support sync invoke.
    if (request.getInvokeType() != null && !RpcConstants.INVOKER_TYPE_SYNC.equals(request.getInvokeType())) {
        return invoker.invoke(request);
    }

    String interfaceResourceName = getInterfaceResourceName(request);
    String methodResourceName = getMethodResourceName(request);

    Entry interfaceEntry = null;
    Entry methodEntry = null;
    try {
        interfaceEntry = SphU.entry(interfaceResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.OUT);
        methodEntry = SphU.entry(methodResourceName, ResourceTypeConstants.COMMON_RPC,
            EntryType.OUT, getMethodArguments(request));

        SofaResponse response = invoker.invoke(request);

        traceResponseException(response, interfaceEntry, methodEntry);
        return response;
    } catch (BlockException e) {
        return SofaRpcFallbackRegistry.getConsumerFallback().handle(invoker, request, e);
    } catch (Throwable t) {
        throw traceOtherException(t, interfaceEntry, methodEntry);
    } finally {
        if (methodEntry != null) {
            methodEntry.exit(1, getMethodArguments(request));
        }

        if (interfaceEntry != null) {
            interfaceEntry.exit();
        }
    }
}
 
Example #23
Source File: SofaResponseHessianSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void decodeObjectByTemplate(AbstractByteBuf data, Map<String, String> context, SofaResponse template)
    throws SofaRpcException {
    try {
        UnsafeByteArrayInputStream inputStream = new UnsafeByteArrayInputStream(data.array());
        Hessian2Input input = new Hessian2Input(inputStream);
        // 根据SerializeType信息决定序列化器
        boolean genericSerialize = context != null && isGenericResponse(
            context.get(RemotingConstants.HEAD_GENERIC_TYPE));
        if (genericSerialize) {
            input.setSerializerFactory(genericSerializerFactory);
            GenericObject genericObject = (GenericObject) input.readObject();
            template.setErrorMsg((String) genericObject.getField("errorMsg"));
            template.setAppResponse(genericObject.getField("appResponse"));
            template.setResponseProps((Map<String, String>) genericObject.getField("responseProps"));
        } else {
            input.setSerializerFactory(serializerFactory);
            SofaResponse tmp = (SofaResponse) input.readObject();
            // copy values to template
            template.setErrorMsg(tmp.getErrorMsg());
            template.setAppResponse(tmp.getAppResponse());
            template.setResponseProps(tmp.getResponseProps());
        }
        input.close();
    } catch (IOException e) {
        throw buildDeserializeError(e.getMessage(), e);
    }
}
 
Example #24
Source File: TestChainFilter7.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    request.getMethodArgs()[0] = request.getMethodArgs()[0] + "_q7";
    SofaResponse response = invoker.invoke(request);
    if (!request.isAsync()) {
        response.setAppResponse(response.getAppResponse() + "_s7");
    }
    return response;
}
 
Example #25
Source File: SofaRequestHessianSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaRequest decodeObject(AbstractByteBuf data, Map<String, String> context) throws SofaRpcException {
    try {
        UnsafeByteArrayInputStream inputStream = new UnsafeByteArrayInputStream(data.array());
        Hessian2Input input = new Hessian2Input(inputStream);
        input.setSerializerFactory(serializerFactory);
        Object object = input.readObject();
        SofaRequest sofaRequest = (SofaRequest) object;
        String targetServiceName = sofaRequest.getTargetServiceUniqueName();
        if (targetServiceName == null) {
            throw buildDeserializeError("Target service name of request is null!");
        }
        String interfaceName = ConfigUniqueNameGenerator.getInterfaceName(targetServiceName);
        sofaRequest.setInterfaceName(interfaceName);

        String[] sig = sofaRequest.getMethodArgSigs();
        Class<?>[] classSig = ClassTypeUtils.getClasses(sig);

        final Object[] args = new Object[sig.length];
        for (int i = 0; i < sofaRequest.getMethodArgSigs().length; ++i) {
            args[i] = input.readObject(classSig[i]);
        }
        sofaRequest.setMethodArgs(args);
        input.close();
        return sofaRequest;
    } catch (IOException e) {
        throw buildDeserializeError(e.getMessage(), e);
    }
}
 
Example #26
Source File: TestSyncFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    interfaceName = request.getInterfaceName();
    targetServiceUniqueName = request.getTargetServiceUniqueName();
    methodName = request.getMethodName();
    invokeType = request.getInvokeType();
    targetAppName = request.getTargetAppName();
    args = request.getMethodArgs();
    return invoker.invoke(request);
}
 
Example #27
Source File: BoltServerProcessor.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 客户端已经超时了(例如在队列里等待太久了),丢弃这个请求
 *
 * @param appName       应用
 * @param serviceName   服务
 * @param remoteAddress 远程地址
 * @return 丢弃的异常
 */
private SofaRpcException clientTimeoutWhenReceiveRequest(String appName, String serviceName, String remoteAddress) {
    String errorMsg = LogCodes.getLog(
        LogCodes.ERROR_DISCARD_TIMEOUT_REQUEST, serviceName, remoteAddress);
    if (LOGGER.isWarnEnabled(appName)) {
        LOGGER.warnWithApp(appName, errorMsg);
    }
    return new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, errorMsg);
}
 
Example #28
Source File: ServiceExceptionInvocationStat.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public long catchException(Throwable t) {
    if (t instanceof SofaRpcException) {
        SofaRpcException exception = (SofaRpcException) t;
        if (exception.getErrorType() == RpcErrorType.CLIENT_TIMEOUT
            || exception.getErrorType() == RpcErrorType.SERVER_BUSY) {
            return exceptionCount.incrementAndGet();
        }
    }
    return exceptionCount.get();
}
 
Example #29
Source File: AsyncHelloServiceImpl.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public String rpcException(String name) {
    RpcInvokeContext context = RpcInvokeContext.getContext();
    context.setTimeout(2000);
    context.setResponseCallback(new BoltSendableResponseCallback() {
        @Override
        public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
            sendSofaException(new SofaRpcException(RpcErrorType.SERVER_BUSY, "bbb"));
        }
    });

    helloService.sayHello(name, 1); // B-异步调用->C
    return null;
}
 
Example #30
Source File: BoltClientTransportTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToRpcException() {
    ClientTransportConfig config1 = new ClientTransportConfig();
    config1.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12222))
        .setContainer("bolt");
    BoltClientTransport transport = new BoltClientTransport(config1);
    Assert.assertTrue(transport
        .convertToRpcException(new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, ""))
        instanceof SofaRpcException);
    Assert.assertTrue(transport.convertToRpcException(new InvokeTimeoutException())
        instanceof SofaTimeOutException);
    Assert.assertTrue(transport.convertToRpcException(new InvokeServerBusyException())
        .getErrorType() == RpcErrorType.SERVER_BUSY);
    Assert.assertTrue(transport.convertToRpcException(new SerializationException("xx", true))
        .getErrorType() == RpcErrorType.SERVER_SERIALIZE);
    Assert.assertTrue(transport.convertToRpcException(new SerializationException("xx", false))
        .getErrorType() == RpcErrorType.CLIENT_SERIALIZE);
    Assert.assertTrue(transport.convertToRpcException(new DeserializationException("xx", true))
        .getErrorType() == RpcErrorType.SERVER_DESERIALIZE);
    Assert.assertTrue(transport.convertToRpcException(new DeserializationException("xx", false))
        .getErrorType() == RpcErrorType.CLIENT_DESERIALIZE);
    Assert.assertTrue(transport.convertToRpcException(new ConnectionClosedException())
        .getErrorType() == RpcErrorType.CLIENT_NETWORK);
    Assert.assertTrue(transport.convertToRpcException(new InvokeSendFailedException())
        .getErrorType() == RpcErrorType.CLIENT_NETWORK);
    Assert.assertTrue(transport.convertToRpcException(new InvokeServerException())
        .getErrorType() == RpcErrorType.SERVER_UNDECLARED_ERROR);
    Assert.assertTrue(transport.convertToRpcException(new UnsupportedOperationException())
        .getErrorType() == RpcErrorType.CLIENT_UNDECLARED_ERROR);
}