问题
Javadoc has clear rules for documenting the return value and exceptions thrown by a method. But what are we supposed to do for methods that return/throw from within an asynchronous response such as CompletionStage or Future?
If I use @throws
to document exceptions that are thrown asynchronously, the IDE complains that the method doesn't throw the exceptions (directly). And it is right, the method does not.
If I document the long list of exceptions that are thrown asynchronously in the @return
section the resulting documentation is difficult to read.
What is the best practice for this situation? If possible, please reference established libraries as examples.
回答1:
For what it's worth, I'm currently using the following syntax but I don't think it is an established best practice:
/**
* @param symbol the name of a stock ticker
* @return the price of the ticker
* <br> {@code @throws NullPointerException} if {@code symbol} is null
* <br> {@code @throws IOException} if an I/O error occurs
*/
public CompletionStage<BigDecimal> getPrice(String symbol);
My guidelines are as follows:
- Throw all exceptions asynchronously, even for instant failures like argument preconditions. This allows clients to centralize error handling in one place.
- Document exceptions under the
@return
using the same@throws
syntax that is familiar to developers.
The result looks quite decent.
来源:https://stackoverflow.com/questions/49092824/how-to-document-asynchronous-results-exceptions