Skip to content

The only tool you need to know what is happening and how to fix it.

fix: Spring Boot OTel exception handling (#148)

FrameAutomata46067c546f76
diff --git a/.gitignore b/.gitignore
index 38a97d79..d89d0ef3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,7 @@
*.dll
*.so
*.dylib
+*.jar
# Test binary, built with `go test -c`
*.test
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index e66ee6fe..c8ef56a8 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -327,23 +327,27 @@ func (e clientController) Report(c *gin.Context) {
}
var (
- errorMessageRe = regexp.MustCompile(`(?m)^(\*?[\w.]+):\s*.+`)
- absolutePathRe = regexp.MustCompile(`/[^\s:]+/([^/\s:]+:\d+)`)
- versionRe = regexp.MustCompile(`@v[\d.]+`)
- hexRe = regexp.MustCompile(`0x[0-9a-fA-F]+`)
- uuidRe = regexp.MustCompile(`[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`)
- largeNumberRe = regexp.MustCompile(`(^|[^:\d])(\d{5,})($|[^\d])`)
- emailRe = regexp.MustCompile(`[\w.\-]+@[\w.\-]+\.\w+`)
- ipRe = regexp.MustCompile(`\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?`)
- goroutineRe = regexp.MustCompile(`goroutine \d+`)
- spacesRe = regexp.MustCompile(`[ \t]+`)
- newlinesRe = regexp.MustCompile(`\n+`)
+ errorMessageRe = regexp.MustCompile(`(?m)^(\*?[\w.]+):\s*.+`)
+ causedByRe = regexp.MustCompile(`(?m)^(Caused by:\s*[\w.$]+):\s*.+`)
+ absolutePathRe = regexp.MustCompile(`/[^\s:]+/([^/\s:]+:\d+)`)
+ versionRe = regexp.MustCompile(`@v[\d.]+`)
+ hexRe = regexp.MustCompile(`0x[0-9a-fA-F]+`)
+ uuidRe = regexp.MustCompile(`[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`)
+ largeNumberRe = regexp.MustCompile(`(^|[^:\d])(\d{5,})($|[^\d])`)
+ emailRe = regexp.MustCompile(`[\w.\-]+@[\w.\-]+\.\w+`)
+ ipRe = regexp.MustCompile(`\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?`)
+ goroutineRe = regexp.MustCompile(`goroutine \d+`)
+ javaLineNumRe = regexp.MustCompile(`\((\w[\w.$]*\.(?:java|kt|scala)):\d+\)`)
+ javaEllipsisRe = regexp.MustCompile(`\.\.\. \d+ more`)
+ spacesRe = regexp.MustCompile(`[ \t]+`)
+ newlinesRe = regexp.MustCompile(`\n+`)
)
func ComputeExceptionHash(stackTrace string, isMessage bool) string {
normalized := stackTrace
if !isMessage {
+ normalized = causedByRe.ReplaceAllString(normalized, "$1")
normalized = errorMessageRe.ReplaceAllString(normalized, "$1")
normalized = absolutePathRe.ReplaceAllString(normalized, "$1")
normalized = versionRe.ReplaceAllString(normalized, "")
@@ -353,6 +357,8 @@ func ComputeExceptionHash(stackTrace string, isMessage bool) string {
normalized = emailRe.ReplaceAllString(normalized, "<email>")
normalized = ipRe.ReplaceAllString(normalized, "<ip>")
normalized = goroutineRe.ReplaceAllString(normalized, "goroutine <n>")
+ normalized = javaLineNumRe.ReplaceAllString(normalized, "($1)")
+ normalized = javaEllipsisRe.ReplaceAllString(normalized, "... more")
normalized = spacesRe.ReplaceAllString(normalized, " ")
normalized = newlinesRe.ReplaceAllString(normalized, "\n")
}
diff --git a/backend/app/controllers/clientcontrollers/client.controller_test.go b/backend/app/controllers/clientcontrollers/client.controller_test.go
index 394be7c6..6f6a747f 100644
--- a/backend/app/controllers/clientcontrollers/client.controller_test.go
+++ b/backend/app/controllers/clientcontrollers/client.controller_test.go
@@ -5,6 +5,51 @@ import (
"testing"
)
+func TestComputeExceptionHash_Java(t *testing.T) {
+ // Two occurrences of the same exception with different user IDs in the
+ // message must produce the same hash (message is stripped).
+ stackA := "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.UserService.getUser(UserService.java:38)\n\t... 52 more"
+ stackB := "org.springframework.dao.EmptyResultDataAccessException: No user found for id 99999\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.UserService.getUser(UserService.java:38)\n\t... 52 more"
+ if ComputeExceptionHash(stackA, false) != ComputeExceptionHash(stackB, false) {
+ t.Error("same exception with different messages should have the same hash")
+ }
+
+ // Line number changes must not change the hash.
+ stackC := "java.lang.NullPointerException: Cannot invoke method\n\tat com.example.Service.run(Service.java:10)\n\tat com.example.Main.main(Main.java:5)"
+ stackD := "java.lang.NullPointerException: Cannot invoke method\n\tat com.example.Service.run(Service.java:99)\n\tat com.example.Main.main(Main.java:42)"
+ if ComputeExceptionHash(stackC, false) != ComputeExceptionHash(stackD, false) {
+ t.Error("same exception at different line numbers should have the same hash")
+ }
+
+ // Different ellipsis counts must not change the hash.
+ stackE := "java.io.IOException: timeout\n\tat com.example.Client.send(Client.java:20)\n\t... 10 more"
+ stackF := "java.io.IOException: timeout\n\tat com.example.Client.send(Client.java:20)\n\t... 73 more"
+ if ComputeExceptionHash(stackE, false) != ComputeExceptionHash(stackF, false) {
+ t.Error("same exception with different ellipsis counts should have the same hash")
+ }
+
+ // Caused-by chains with different messages must not change the hash.
+ stackG := "org.springframework.web.client.RestClientException: error\n\tat com.example.Api.call(Api.java:15)\nCaused by: java.net.SocketTimeoutException: connect timed out\n\tat java.net.Socket.connect(Socket.java:633)"
+ stackH := "org.springframework.web.client.RestClientException: error\n\tat com.example.Api.call(Api.java:15)\nCaused by: java.net.SocketTimeoutException: Read timed out after 30000ms\n\tat java.net.Socket.connect(Socket.java:633)"
+ if ComputeExceptionHash(stackG, false) != ComputeExceptionHash(stackH, false) {
+ t.Error("same caused-by chain with different messages should have the same hash")
+ }
+
+ // Kotlin stack frames (.kt extension) must have line numbers stripped too.
+ stackI := "java.lang.IllegalStateException: bad state\n\tat com.example.Service.process(Service.kt:55)"
+ stackJ := "java.lang.IllegalStateException: bad state\n\tat com.example.Service.process(Service.kt:88)"
+ if ComputeExceptionHash(stackI, false) != ComputeExceptionHash(stackJ, false) {
+ t.Error("same Kotlin exception at different line numbers should have the same hash")
+ }
+
+ // Structurally different exceptions must NOT have the same hash.
+ stackK := "java.lang.NullPointerException: npe\n\tat com.example.Foo.bar(Foo.java:1)"
+ stackL := "java.lang.IllegalArgumentException: iae\n\tat com.example.Foo.bar(Foo.java:1)"
+ if ComputeExceptionHash(stackK, false) == ComputeExceptionHash(stackL, false) {
+ t.Error("different exception types should have different hashes")
+ }
+}
+
func TestIsEmptyRaw(t *testing.T) {
cases := []struct {
name string
diff --git a/backend/app/controllers/otelcontrollers/testdata/node_sign_in.json.golden.json b/backend/app/controllers/otelcontrollers/testdata/node_sign_in.json.golden.json
index 931f6439..40da201c 100644
--- a/backend/app/controllers/otelcontrollers/testdata/node_sign_in.json.golden.json
+++ b/backend/app/controllers/otelcontrollers/testdata/node_sign_in.json.golden.json
@@ -35,7 +35,7 @@
"exceptionCount": 1,
"exceptions": [
{
- "stackTrace": "APIError: Invalid email or password\nAPIError: Invalid email or password",
+ "stackTrace": "APIError: Invalid email or password",
"traceType": "task"
}
],
diff --git a/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json b/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json
new file mode 100644
index 00000000..a50e8bd8
--- /dev/null
+++ b/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json
@@ -0,0 +1,74 @@
+{
+ "resourceSpans": [
+ {
+ "resource": {
+ "attributes": [
+ {"key": "service.name", "value": {"stringValue": "user-service"}},
+ {"key": "service.version", "value": {"stringValue": "2.1.0"}},
+ {"key": "telemetry.sdk.name", "value": {"stringValue": "opentelemetry"}},
+ {"key": "telemetry.sdk.language", "value": {"stringValue": "java"}},
+ {"key": "telemetry.sdk.version", "value": {"stringValue": "1.44.0"}}
+ ]
+ },
+ "scopeSpans": [
+ {
+ "scope": {"name": "io.opentelemetry.spring-webmvc-6.0", "version": "2.13.0-alpha"},
+ "spans": [
+ {
+ "traceId": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
+ "spanId": "1122334455667788",
+ "name": "GET /api/users/{id}",
+ "kind": "SPAN_KIND_SERVER",
+ "startTimeUnixNano": "1700000000000000000",
+ "endTimeUnixNano": "1700000000150000000",
+ "attributes": [
+ {"key": "http.request.method", "value": {"stringValue": "GET"}},
+ {"key": "http.route", "value": {"stringValue": "/api/users/{id}"}},
+ {"key": "http.response.status_code", "value": {"intValue": "500"}},
+ {"key": "url.path", "value": {"stringValue": "/api/users/99999"}},
+ {"key": "server.address", "value": {"stringValue": "localhost"}},
+ {"key": "server.port", "value": {"intValue": "8080"}},
+ {"key": "network.protocol.version", "value": {"stringValue": "1.1"}},
+ {"key": "user_agent.original", "value": {"stringValue": "PostmanRuntime/7.32.3"}}
+ ],
+ "events": [
+ {
+ "timeUnixNano": "1700000000140000000",
+ "name": "exception",
+ "attributes": [
+ {"key": "exception.type", "value": {"stringValue": "org.springframework.dao.EmptyResultDataAccessException"}},
+ {"key": "exception.message", "value": {"stringValue": "Incorrect result size: expected 1, actual 0"}},
+ {"key": "exception.stacktrace", "value": {"stringValue": "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.userservice.repository.UserRepository.findById(UserRepository.java:42)\n\tat com.example.userservice.service.UserService.getUser(UserService.java:38)\n\tat com.example.userservice.controller.UserController.getUser(UserController.java:28)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\n\t... 52 more"}},
+ {"key": "exception.escaped", "value": {"boolValue": true}}
+ ]
+ }
+ ],
+ "status": {"code": "STATUS_CODE_ERROR", "message": "Incorrect result size: expected 1, actual 0"}
+ }
+ ]
+ },
+ {
+ "scope": {"name": "io.opentelemetry.jdbc", "version": "2.13.0-alpha"},
+ "spans": [
+ {
+ "traceId": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
+ "spanId": "aabbccddeeff0011",
+ "parentSpanId": "1122334455667788",
+ "name": "SELECT users",
+ "kind": "SPAN_KIND_CLIENT",
+ "startTimeUnixNano": "1700000000050000000",
+ "endTimeUnixNano": "1700000000130000000",
+ "attributes": [
+ {"key": "db.system", "value": {"stringValue": "postgresql"}},
+ {"key": "db.operation.name", "value": {"stringValue": "SELECT"}},
+ {"key": "db.sql.table", "value": {"stringValue": "users"}},
+ {"key": "db.query.text", "value": {"stringValue": "SELECT id, email, name FROM users WHERE id = ?"}}
+ ],
+ "status": {}
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json.golden.json b/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json.golden.json
new file mode 100644
index 00000000..b3058fae
--- /dev/null
+++ b/backend/app/controllers/otelcontrollers/testdata/spring_boot_exception.json.golden.json
@@ -0,0 +1,30 @@
+{
+ "endpointCount": 1,
+ "endpoints": [
+ {
+ "endpoint": "GET /api/users/{id}",
+ "statusCode": 500,
+ "serverName": "user-service",
+ "appVersion": "2.1.0"
+ }
+ ],
+ "taskCount": 0,
+ "spanCount": 1,
+ "spans": [
+ {
+ "name": "SELECT id, email, name FROM users WHERE id = ?",
+ "linkedToParent": true
+ }
+ ],
+ "exceptionCount": 1,
+ "exceptions": [
+ {
+ "stackTrace": "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.userservice.repository.UserRepository.findById(UserRepository.java:42)\n\tat com.example.userservice.service.UserService.getUser(UserService.java:38)\n\tat com.example.userservice.controller.UserController.getUser(UserController.java:28)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\n\t... 52 more",
+ "traceType": "endpoint"
+ }
+ ],
+ "aiTraceCount": 0,
+ "aiTraces": [],
+ "conversationCount": 0,
+ "allSpansLinked": true
+}
\ No newline at end of file
diff --git a/backend/app/controllers/otelcontrollers/trace_converter.go b/backend/app/controllers/otelcontrollers/trace_converter.go
index d5373c96..1cf3263d 100644
--- a/backend/app/controllers/otelcontrollers/trace_converter.go
+++ b/backend/app/controllers/otelcontrollers/trace_converter.go
@@ -168,7 +168,7 @@ func convertTraces(projectId uuid.UUID, req *coltracepb.ExportTraceServiceReques
if event.Name == "exception" {
exc := buildException(
projectId, traceId, traceType, event,
- serverName, appVersion,
+ allAttrs, serverName, appVersion,
)
exc.DistributedTraceId = distributedTraceId
exceptions = append(exceptions, exc)
@@ -284,6 +284,7 @@ func buildException(
projectId, traceId uuid.UUID,
traceType string,
event *tracepb.Span_Event,
+ spanAttrs map[string]string,
serverName, appVersion string,
) models.ExceptionStackTrace {
eventAttrs := event.Attributes
@@ -302,6 +303,7 @@ func buildException(
ExceptionHash: hash,
StackTrace: stackTrace,
RecordedAt: nanoToTime(event.TimeUnixNano),
+ Attributes: spanAttrs,
AppVersion: appVersion,
ServerName: serverName,
}
@@ -481,7 +483,10 @@ func formatExceptionStackTrace(excType, excMessage, excStacktrace string) string
}
}
if excStacktrace != "" {
- if header != "" {
+ // JVM OTel agents embed the exception class name as the first line of the
+ // stacktrace (e.g. "java.lang.RuntimeException: msg\n\tat ..."). Skip
+ // prepending the header when it's already there to avoid a duplicate line.
+ if header != "" && (excType == "" || !strings.HasPrefix(excStacktrace, excType)) {
return fmt.Sprintf("%s\n%s", header, excStacktrace)
}
return excStacktrace
diff --git a/backend/app/controllers/otelcontrollers/trace_converter_test.go b/backend/app/controllers/otelcontrollers/trace_converter_test.go
index 5d546b56..d55f2b32 100644
--- a/backend/app/controllers/otelcontrollers/trace_converter_test.go
+++ b/backend/app/controllers/otelcontrollers/trace_converter_test.go
@@ -79,6 +79,7 @@ func TestConvertTraces_Snapshot(t *testing.T) {
{"openrouter_ai_trace", "testdata/openrouter_ai_trace.json"},
{"node_better_auth", "testdata/node_better_auth.json"},
{"node_sign_in", "testdata/node_sign_in.json"},
+ {"spring_boot_exception", "testdata/spring_boot_exception.json"},
}
for _, tt := range tests {
@@ -388,6 +389,62 @@ func TestTraceIdResolution_CrossScope(t *testing.T) {
}
}
+func TestFormatExceptionStackTrace(t *testing.T) {
+ tests := []struct {
+ name string
+ excType string
+ excMessage string
+ excStacktrace string
+ want string
+ }{
+ {
+ name: "go style - no stacktrace",
+ excType: "RuntimeError",
+ excMessage: "something failed",
+ excStacktrace: "",
+ want: "RuntimeError: something failed",
+ },
+ {
+ name: "go style - with stacktrace that doesn't start with type",
+ excType: "RuntimeError",
+ excMessage: "something failed",
+ excStacktrace: "goroutine 1 [running]:\nmain.foo()\n\t/app/main.go:10",
+ want: "RuntimeError: something failed\ngoroutine 1 [running]:\nmain.foo()\n\t/app/main.go:10",
+ },
+ {
+ // Java/JVM OTel agents include the full "Type: message\n\tat ..." in
+ // exception.stacktrace, so we must not prepend a duplicate header.
+ name: "java style - stacktrace already starts with exception type",
+ excType: "org.springframework.dao.EmptyResultDataAccessException",
+ excMessage: "Incorrect result size: expected 1, actual 0",
+ excStacktrace: "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.UserService.getUser(UserService.java:38)",
+ want: "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0\n\tat org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:90)\n\tat com.example.UserService.getUser(UserService.java:38)",
+ },
+ {
+ name: "java style - type only, no message",
+ excType: "java.lang.NullPointerException",
+ excMessage: "",
+ excStacktrace: "java.lang.NullPointerException\n\tat com.example.Service.run(Service.java:10)",
+ want: "java.lang.NullPointerException\n\tat com.example.Service.run(Service.java:10)",
+ },
+ {
+ name: "empty everything",
+ excType: "",
+ excMessage: "",
+ excStacktrace: "",
+ want: "unknown exception",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := formatExceptionStackTrace(tt.excType, tt.excMessage, tt.excStacktrace)
+ if got != tt.want {
+ t.Errorf("formatExceptionStackTrace() =\n%q\nwant:\n%q", got, tt.want)
+ }
+ })
+ }
+}
+
// --- Helpers ---
func makeAttrs(key, val string) []*commonpb.KeyValue {
diff --git a/docs/pages/client/otel/index.mdx b/docs/pages/client/otel/index.mdx
index eb1a8080..1f3de17d 100644
--- a/docs/pages/client/otel/index.mdx
+++ b/docs/pages/client/otel/index.mdx
@@ -65,6 +65,25 @@ const metricExporter = new OTLPMetricExporter({
The same pattern applies to any language — set the OTLP/HTTP endpoint and the `Authorization` header in your exporter config.
+## Quick Start: Spring Boot (Java Agent)
+
+The [OpenTelemetry Java agent](https://opentelemetry.io/docs/zero-code/java/agent/) instruments Spring Boot applications with zero code changes. Download the agent JAR and pass it to the JVM:
+
+```bash
+java \
+ -javaagent:opentelemetry-javaagent.jar \
+ -Dotel.service.name=my-spring-app \
+ -Dotel.exporter.otlp.endpoint=https://<your-instance>/api/otel \
+ -Dotel.exporter.otlp.headers="Authorization=Bearer <project_token>" \
+ -Dotel.metrics.exporter=none \
+ -Dotel.logs.exporter=none \
+ -jar target/my-app.jar
+```
+
+Setting `OTEL_EXPORTER_OTLP_ENDPOINT` to `…/api/otel` works too — the agent appends `/v1/traces` automatically, which matches Traceway's ingest path.
+
+Exceptions thrown in your controllers are automatically captured as span events and appear in **Issues**, grouped by exception class across deployments regardless of differing error messages or line numbers.
+
## Quick Start: OTel Collector
If you already run an [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) or want a central pipeline that fans out to multiple backends, you can route data through it. **This is optional** — the direct SDK export above works without a Collector.