在 Cyclops React "Try with Resources" 块中,我想将 an 映射IOException到自定义异常类型。我也用 Javaslang 尝试过这个,但似乎不太灵活,因为它对所有异常都一视同仁。
代码示例:
private static Try<String, ConnectionError> readString() {
// Socket is a thread-local static field
final Try<String, IOException> string = Try.catchExceptions(IOException.class)
.init(() -> new BufferedReader(new InputStreamReader(socket.get().getInputStream())))
.tryWithResources(BufferedReader::readLine);
return string.isSuccess() ? Try.success(string.get()) :
Try.failure(new ConnectionError("Could not read from server", string.failureGet()));
}
Run Code Online (Sandbox Code Playgroud)
这可以以更优雅的方式完成吗?还是没有任何意义,返回会更好Try<String, IOException>?
免责声明:我是使用 Cyclops React 库和一般函数式编程的新手,所以我可能有严重的概念误解。