sofastack / sofa-bolt

SOFABolt is a lightweight, easy to use and high performance remoting framework based on Netty.
https://www.sofastack.tech/projects/sofa-bolt/
Apache License 2.0
2.4k stars 856 forks source link

SyncUserProcessor和AsyncUserProcessor保持相同的业务抛异常语义。即服务端异步处理请求时,如果AsyncUserProcessor处理过程中遭遇exception,调用端可以通过catch exception进行处理,而不是通过instance of判断响应的类型。 #317

Closed welkinxu closed 1 year ago

welkinxu commented 1 year ago

现在调用端的处理AsyncUserProcessor回写异常的方式: Object rsp = (Object) client.invokeSync(addr, req, 3000); if(rsp instance of Exeception ) { // 异常处理 } else { // 正常响应处理 Response rsp1 = (Response) rsp; }

我们期望调用端可以再try-catch中处理异常,保持与服务端sync-processor同样的语义: try { Response rsp = (Respnse)client.invokeSync(addr, req, 3000); }catch(Exception e){ }

期望AsyncContext 可以新增sendException方法: public interface AsyncContext { void sendResponse(Object responseObject); void sendException(Exception ex); }

具体在RpcAsyncContext中的实现,可以参考如下代码,将业务异常包装为ExceptionResponse而不是普通正常响应的Response:

@Override
public void sendResponse(Object responseObject) {
    if (isResponseSentAlready.compareAndSet(false, true)) {
        processor.sendResponseIfNecessary(this.ctx, cmd.getType(), processor
            .getCommandFactory().createResponse(responseObject, this.cmd));
    } else {
        throw new IllegalStateException("Should not send rpc response repeatedly!");
    }
}
@Override
public void sendException(Exception ex) {
    if (isResponseSentAlready.compareAndSet(false, true)) {
        processor.sendResponseIfNecessary(this.ctx, cmd.getType(), processor
                .getCommandFactory().createExceptionResponse(this.cmd.getId(), ResponseStatus.SERVER_EXCEPTION, ex));
    } else {
        throw new IllegalStateException("Should not send rpc response repeatedly!");
    }
}
chuailiwu commented 1 year ago

it is a good idea,hope you can create a pr for it!

welkinxu commented 1 year ago

it is a good idea,hope you can create a pr for it!

OK, I'd love to do this!

welkinxu commented 1 year ago

@chuailiwu hi,pr has been submitted, please review。https://github.com/sofastack/sofa-bolt/pull/319