vipcxj / jasync

make async-await code style available in java just like csharp and es6
Apache License 2.0
129 stars 14 forks source link

Issue with uncaught exceptions #10

Closed knuclechan closed 2 years ago

knuclechan commented 2 years ago

If an exception is not caught and re-throw in the @Async method, the exception is gone.

Let me use your example (simplified) to explain. I assume salaryRepository.findSalaryByDeparmentEmployee returns a mono. If the repository throws an exception (returned error mono) , I would expect the mono unwrapped at getEmployeeSalaryByDepartment is an error mono too, but it is a null value mono instead. The exception is gone.

But if I catch and re-throw the error in the @Async method, then the unwrapped mono is an error mono.

I think it is reasonable to assume that uncaught exception should be passed alone instead of swallowed. If there is implementation difficulty, I think it would be better to reminder others to catch exceptions in the @Async method.

@RestController
@RequestMapping("/employees")
public class MyRestController {

    @Inject
    private SalaryRepository salaryRepository;

    @Async()
    private JPromise<Double> _getEmployeeTotalSalaryByDepartment(String department) {
        Salary salary = Promises.from(salaryRepository.findSalaryByDeparmentEmployee(department)).await();
        return JAsync.just(salary.total);
    }

    // This is a normal webflux method.
    @GetMapping("/{department}/salary")
    public Mono<Double> getEmployeeSalaryByDepartment(@PathVariable String department) { 
        // Use unwrap method to transform the JPromise object back to the Mono object.
        return _getEmployeeTotalSalaryByDepartment(department).unwrap(Mono.class);
    }
}
vipcxj commented 2 years ago

Have you try to catch the exception in the getEmployeeSalaryByDepartment method?

    @GetMapping("/{department}/salary")
    public Mono<Double> getEmployeeSalaryByDepartment(@PathVariable String department) { 
        // Use unwrap method to transform the JPromise object back to the Mono object.
        return _getEmployeeTotalSalaryByDepartment(department).unwrap(Mono.class).onErrorResume(Throwable.class, e -> {
            System.out.println("I found an error: " + e.getMessage());
            return Mono.empty();
        });
    }

If the console print I found an error: XXX, even getEmployeeSalaryByDepartment does not return an error mono, the error is not swallowed. Otherwise, it is really a bug, I will try to fix it.

vipcxj commented 2 years ago

Any news? I will close the issue if no response in a few days

vipcxj commented 2 years ago

close because of no response.