Skip to content

Commit 88dc031

Browse files
runningcodeclaude
andcommitted
fix(dsn): Give a clear error message for a malformed port
Parse the port in a dedicated helper that reports the offending value ("Invalid DSN: Invalid port 'abc'.") instead of leaking the raw NumberFormatException text. Narrow the catch to URISyntaxException now that the port is the only parseInt, and add a test. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent d5aecc2 commit 88dc031

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

sentry/src/main/java/io/sentry/Dsn.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ URI getSentryUri() {
8888
final String hostPort = hostAndPath.substring(0, firstSlash);
8989
final int portColon = portSeparatorIndex(hostPort);
9090
final String host = portColon < 0 ? hostPort : hostPort.substring(0, portColon);
91-
final int port = portColon < 0 ? -1 : Integer.parseInt(hostPort.substring(portColon + 1));
91+
final int port = portColon < 0 ? -1 : parsePort(hostPort.substring(portColon + 1));
9292

9393
final String rawPath = stripTrailingSlash(collapseSlashes(hostAndPath.substring(firstSlash)));
9494
final int projectIdStart = rawPath.lastIndexOf('/') + 1;
@@ -100,11 +100,19 @@ URI getSentryUri() {
100100

101101
sentryUri = new URI(scheme, null, host, port, path + "api/" + projectId, null, null);
102102
orgId = extractOrgId(host);
103-
} catch (URISyntaxException | NumberFormatException e) {
103+
} catch (URISyntaxException e) {
104104
throw new IllegalArgumentException("Invalid DSN: " + e.getMessage(), e);
105105
}
106106
}
107107

108+
private static int parsePort(final @NotNull String portString) {
109+
try {
110+
return Integer.parseInt(portString);
111+
} catch (NumberFormatException e) {
112+
throw new IllegalArgumentException("Invalid DSN: Invalid port '" + portString + "'.", e);
113+
}
114+
}
115+
108116
// Drops the query string and/or fragment, whichever appears first, from the host onwards.
109117
private static @NotNull String stripQueryAndFragment(
110118
final @NotNull String dsn, final int fromIndex) {

sentry/src/test/java/io/sentry/DsnTest.kt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,12 @@ class DsnTest {
159159
assertThat(ex).hasMessageThat().isEqualTo("Invalid DSN: A Project Id is required.")
160160
}
161161

162+
@Test
163+
fun `when port is not a number, throws exception`() {
164+
val ex = assertFailsWith<IllegalArgumentException> { Dsn("http://key@host:abc/1") }
165+
assertThat(ex).hasMessageThat().isEqualTo("Invalid DSN: Invalid port 'abc'.")
166+
}
167+
162168
@Test
163169
fun `dsn parsed with multiple path segments`() {
164170
val dsn = Dsn("https://key@host/path/to/sentry/id")

0 commit comments

Comments
 (0)