1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http;
28
29 import java.io.IOException;
30 import java.net.ConnectException;
31 import java.net.InetAddress;
32 import java.net.SocketTimeoutException;
33 import java.util.Arrays;
34
35 import org.apache.hc.core5.annotation.Internal;
36 import org.apache.hc.core5.net.NamedEndpoint;
37
38
39
40
41
42
43 @Internal
44 public final class ConnectExceptionSupport {
45
46 public static ConnectTimeoutException createConnectTimeoutException(
47 final IOException cause, final NamedEndpoint namedEndpoint, final InetAddress... remoteAddresses) {
48 final String message = "Connect to " +
49 (namedEndpoint != null ? namedEndpoint : "remote endpoint") +
50 (remoteAddresses != null && remoteAddresses.length > 0 ? " " + Arrays.asList(remoteAddresses) : "") +
51 ((cause != null && cause.getMessage() != null) ? " failed: " + cause.getMessage() : " timed out");
52 return new ConnectTimeoutException(message, namedEndpoint);
53 }
54
55 public static HttpHostConnectException createHttpHostConnectException(
56 final IOException cause,
57 final NamedEndpoint namedEndpoint,
58 final InetAddress... remoteAddresses) {
59 final String message = "Connect to " +
60 (namedEndpoint != null ? namedEndpoint : "remote endpoint") +
61 (remoteAddresses != null && remoteAddresses.length > 0 ? " " + Arrays.asList(remoteAddresses) : "") +
62 ((cause != null && cause.getMessage() != null) ? " failed: " + cause.getMessage() : " refused");
63 return new HttpHostConnectException(message, namedEndpoint);
64 }
65
66 public static IOException enhance(
67 final IOException cause, final NamedEndpoint namedEndpoint, final InetAddress... remoteAddresses) {
68 if (cause instanceof SocketTimeoutException) {
69 final IOException ex = createConnectTimeoutException(cause, namedEndpoint, remoteAddresses);
70 ex.setStackTrace(cause.getStackTrace());
71 return ex;
72 } else if (cause instanceof ConnectException) {
73 if ("Connection timed out".equals(cause.getMessage())) {
74 final IOException ex = createConnectTimeoutException(cause, namedEndpoint, remoteAddresses);
75 ex.initCause(cause);
76 return ex;
77 }
78 final IOException ex = createHttpHostConnectException(cause, namedEndpoint, remoteAddresses);
79 ex.setStackTrace(cause.getStackTrace());
80 return ex;
81 } else {
82 return cause;
83 }
84 }
85
86 }