package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import util.function.Expected;
import util.function.Expected;
public class Demo {
enum URLError {
MALFORMED_URL, IO_ERROR
}
/**
* Opens and read the provided URL
*
* @param urlString
* the URL as String
* @return an Expected with the content as String, in case of an error the
* corresponding URLError will be returned
*/
public static Expected<String, URLError> readURL(String urlString) {
URL url;
try {
url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) {
String line;
while ((line = br.readLine()) != null)
sb.append(line);
return Expected.expected(new String(sb.toString()));
}
} catch (MalformedURLException e) {
return Expected.unexpected(URLError.MALFORMED_URL);
} catch (IOException e) {
return Expected.unexpected(URLError.IO_ERROR);
}
}
public void someFunc() {
// Functional programming using 'ifValue', 'map' and 'bind' to process
// expected values
final String URLs[] = { "https://google.com", "https://bing.com", "https://yahoo.com" };
Arrays.asList(URLs).parallelStream().map(Demo::readURL).forEach(e -> e.ifValue(System.out::println));
// Error handling using the expected
Expected<String, URLError> expected = readURL("<?!>");
if (expected.hasErrorValue()) {
URLError error = expected.getErrorValue();
// TODO cope with error
}
}
}
-
Notifications
You must be signed in to change notification settings - Fork 0
roehrdor/jexpected
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
About
Expected Error Handling implementation in Java
Topics
Resources
Stars
Watchers
Forks
Releases
No releases published
Packages 0
No packages published