feat[net]: 新增异步异常回调方法

This commit is contained in:
jaysunxiao
2021-08-23 19:46:27 +08:00
parent 438ec37095
commit cc47ff6568
3 changed files with 28 additions and 7 deletions
@@ -236,21 +236,25 @@ public class PacketDispatcher implements IPacketDispatcher {
}
return response;
})
.whenCompleteAsync((responsePacket, e) -> {
.whenCompleteAsync((responsePacket, throwable) -> {
try {
PacketSignal.removeSignalAttachment(clientAttachment);
// 如果有异常的话,whenCompleteAsync的下一个thenAccept不会执行
if (e != null) {
logger.error(ExceptionUtils.getMessage(e));
return;
}
// 接收者在同步或异步的消息处理中,又调用了异步的方法,这时候threadServerAttachment不为空
if (serverSignalPacketAttachment != null) {
serverReceiveSignalPacketAttachment.set(serverSignalPacketAttachment);
}
// 如果有异常的话,whenCompleteAsync的下一个thenAccept不会执行
if (throwable != null) {
var exceptionCallback = asyncAnswer.getExceptionCallback();
if (exceptionCallback != null) {
exceptionCallback.accept(throwable);
}
logger.error(ExceptionUtils.getMessage(throwable));
return;
}
// 异步返回,回调业务逻辑
asyncAnswer.setFuturePacket((T) responsePacket);
asyncAnswer.consume();
@@ -33,6 +33,9 @@ public class AsyncAnswer<T extends IPacket> implements IAsyncAnswer<T> {
private Runnable askCallback;
private Consumer<Throwable> exceptionCallback;
@Override
public IAsyncAnswer<T> thenAccept(Consumer<T> consumer) {
consumerList.add(consumer);
@@ -45,6 +48,11 @@ public class AsyncAnswer<T extends IPacket> implements IAsyncAnswer<T> {
askCallback.run();
}
@Override
public void exceptionally(Consumer<Throwable> exceptionCallback) {
this.exceptionCallback = exceptionCallback;
}
public void consume() {
consumerList.forEach(it -> it.accept(futurePacket));
}
@@ -72,4 +80,8 @@ public class AsyncAnswer<T extends IPacket> implements IAsyncAnswer<T> {
public void setAskCallback(Runnable askCallback) {
this.askCallback = askCallback;
}
public Consumer<Throwable> getExceptionCallback() {
return exceptionCallback;
}
}
@@ -30,4 +30,9 @@ public interface IAsyncAnswer<T extends IPacket> {
*/
void whenComplete(Consumer<T> consumer);
/**
* 当异步种有异常会回调的方法
*/
void exceptionally(Consumer<Throwable> exceptionCallback);
}