Closed Alice52 closed 3 years ago
[java内]
@Async
static final class AsyncRun extends ForkJoinTask<Void> implements Runnable, AsynchronousCompletionTask { public void run() { ... try { f.run(); d.completeNull(); } catch (Throwable ex) { d.completeThrowable(ex); } ... } }
@Async 注解是怎么实现子线程可以捕获异常的
Callable<Object> task = () -> { try { Object result = invocation.proceed(); if (result instanceof Future) { return ((Future<?>) result).get(); } } catch (ExecutionException ex) { handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments()); } catch (Throwable ex) { handleError(ex, userDeclaredMethod, invocation.getArguments()); } return null; }; @Nullable protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) { if (CompletableFuture.class.isAssignableFrom(returnType)) { return CompletableFuture.supplyAsync(() -> { try { return task.call(); } catch (Throwable ex) { throw new CompletionException(ex); } }, executor); } else if (ListenableFuture.class.isAssignableFrom(returnType)) { return ((AsyncListenableTaskExecutor) executor).submitListenable(task); } else if (Future.class.isAssignableFrom(returnType)) { return executor.submit(task); } else { executor.submit(task); return null; } }
子线程常见的异常处理方式
[java内]
CompletableFuture 中异常问题
@Async
内的子线程异常默认就可以被 mvc 的全局异常处理器处理Reference
@Async
注解是怎么实现子线程可以捕获异常的