Sobes.tech
Middle+

If you were developing a library for working with HTTP, would you use exceptions for error handling or other mechanisms?

sobes.tech AI

Answer from AI

Would use exceptions to handle exceptional situations such as:

  • Connection error (e.g., ConnectException).
  • Timeout (e.g., SocketTimeoutException).
  • Invalid URL (e.g., MalformedURLException).
  • HTTP protocol errors with status codes 4xx and 5xx (e.g., HttpResponseException indicating the status).

For handling successful HTTP responses with status codes 2xx and 3xx, as well as working with response content, it is preferable to use a return type that represents the result of the operation, such as a response object with access to headers, body, and status.

public interface HttpClient {
    HttpResponse executeRequest(HttpRequest request) throws IOException, HttpRequestException; // IOException for network issues, HttpRequestException for request problems
}

public class HttpResponse {
    private final int statusCode;
    private final Map<String, String> headers;
    private final InputStream body;

    // constructor, getters
}

public class HttpRequestException extends Exception {
    private final int statusCode; // For 4xx/5xx errors

    // constructor, getters
}
If you were developing a library for working with… - sobes.tech