fix(go): read nested and inferred error messages in typed errors

Merged
2Y
7d ago
+1126-41

Why

Go typed errors built Error() only from a top-level field marked x-speakeasy-error-message: true. Otherwise Error() returned a JSON dump of the error struct. A common error envelope keeps the message one level down:

{"error": {"message": "Something went wrong.", "code": "invalid_request"}}

TypeScript, Python, C# and Java (#201) resolve this through the shared getOrInferErrorMessageFieldDeep helper (templates/templates/common/common/utils.ts). It finds a marked field at any depth, or else infers a top-level message string, or else error.message. Go ignored a nested marker and did no inference.

What changed

  • templateErrorMessage (templates/templates/go/includes/templating.ts) now uses getOrInferErrorMessageFieldDeep when there is no top-level marker. Each step of the path is nil-checked, and the JSON dump remains the fallback when a value along the path is nil:
    func (e *CreateWidgetError) Error() string {
    	if v0 := e.ErrorInfo; v0 != nil {
    		if v0.Message != nil {
    			return *v0.Message
    		}
    	}
    
    	data, _ := json.Marshal(e)
    	return string(data)
    }
    
  • Optional+nullable fields on model structs are unwrapped through OptionalNullable.Get() when nullableOptionalWrapper is enabled. Error structs never use the wrapper.
  • Field access follows the template that declares each struct. Error structs use their error-scoped field names (Error becomes ErrorInfo or Error_). Every other struct uses its model field names, including union error members that remain classes when sharedErrorComponentsApr2025 is off. Const fields on model structs are unexported, so they are read through their getter.
  • If the field holding the message isn't a string, it is converted with fmt.Sprint. Previously, a marked non-string field at the top level failed to compile.
  • A required+nullable marked field is now dereferenced. Previously the pointer check only looked at Optional, so return e.Field with a *string field failed to compile.
  • A top-level marked string field still takes precedence and keeps its existing generated output.
  • Unskipped errors-optional-nullable-error-message and errors-optional-nullable-error-message-nested, and added Go tests for both. The nested test covers a cause that is both present and absent.
  • The code property of the nullableOptionalErrorMessage and nestedNullableOptionalErrorMessage test schemas is now a string, matching the "code":"512" the test service returns. Go's strict unmarshalling rejected the string for an integer field, which is why these tests were skipped for Go.

Behaviour change

A typed error whose schema has a top-level message string or an error.message string, and no marker, now returns that message from Error() instead of a JSON dump. This matches the other targets. The review SDK shows this in the Error() bodies of BadRequestResponseError, RequestTimeoutError, TaggedError1, TaggedError2, ErrorType2 and the union errors that wrap them. The 501 and union-of-errors primary tests now expect the inferred message.

Testing

  • TARGET=primary make test-go: 770 passed.
  • TARGET=review make build-go regenerated zSDKs/sdk-go; only Error() bodies changed.
  • Updated TestSnapGoMethodCollisionResolution and TestSnapGoErrorUnionDiscriminatorErrorMemberField snapshots. Added TestSnapGoErrorMessageFieldAccess, which covers a union error member under legacy error scoping and a const message field on a nested model.
  • make lint and make check-template-go pass.
  • Generated throwaway SDKs from a focused spec with nullableOptionalWrapper on and off, and checked runtime Error() output for these cases:
    • inferred error.message (required and optional error) and top-level message
    • a marker nested under optional+nullable objects (present and null)
    • a required chain with a nullable final field
    • a top-level required+nullable marker
    • a marked field of each non-string type: integer, string enum, integer enum, untyped, date-time
    • a nested object with an error field, discriminated and non-discriminated union errors, and a recursive schema
    • bigint, decimal, bytes, map and object leaves, and const fields at the top level and nested
  • Markers inside arrays, maps and oneOf members aren't followed (same as TypeScript), so those fall back to the JSON dump.

Public-safety check

  • This change contains no credentials, customer documents, private repository URLs, private filesystem paths, or unredacted private logs.
  • Title, body, comments, and commit messages name no customers or customer-derived identifiers, private paths or trackers, or workflow provenance, and are understandable without private context (.claude/skills/public-repo-communication/SKILL.md).
  • Generated fixtures and review SDK changes are public-safe.
  • I reviewed git diff --check.

Summary by cubic

Generates Error() in Go from nested or inferred message fields instead of the JSON struct dump, matching TypeScript, Python, C#, and Java. The path is fully nil-safe: a nil error receiver or nil union member returns the JSON fallback instead of panicking.

  • Uses the shared deep/inferred lookup: a marked field at any depth, else a top-level message string, else error.message; a top-level marked string still takes precedence.
  • Unwraps optional+nullable model fields through OptionalNullable.Get(), reads const model fields via their getter, and converts non-string fields with fmt.Sprint.
  • Falls back to the JSON dump when any hop is nil or the message is inside arrays, maps, or oneOf members.
  • Fixes compile errors for required+nullable marked fields and marked non-string fields at the top level.
  • Behaves correctly for nil receivers and nil union members instead of panicking.
  • Unskips the optional-nullable error-message tests for Go and changes their code schema property to a string to match the test service.