Skip to content

Structured JSON error responses for API endpoints#110

Merged
andrew merged 2 commits intomainfrom
structured-errors
May 3, 2026
Merged

Structured JSON error responses for API endpoints#110
andrew merged 2 commits intomainfrom
structured-errors

Conversation

@andrew
Copy link
Copy Markdown
Contributor

@andrew andrew commented May 3, 2026

API handlers returned errors via http.Error as text/plain with ad-hoc strings, while the mirror API used a different {"error": "..."} shape and leaked raw err.Error() to clients on job creation failure.

Adds ErrorResponse{Code, Message} in internal/server/errors.go with four stable codes (BAD_REQUEST, NOT_FOUND, UPSTREAM_ERROR, INTERNAL_ERROR) and writeError plus badRequest/notFound/internalError shorthands. All JSON API handlers in api.go, browse.go, mirror_api.go and the /stats endpoint now return:

{"code": "NOT_FOUND", "message": "package not found"}

Enrichment failures now report 502 UPSTREAM_ERROR rather than 500, since the proxy itself is fine.

Two surfaces deliberately left as-is. Protocol handlers in internal/handler/ serve real package-manager clients (npm, pip, cargo, etc.) that expect protocol-native responses, so JSON errors there would break installs. HTML page handlers in server.go (showPackage, showVersion, search/list pages) keep text/plain since they render templates, not JSON.

Swagger @Failure annotations updated to {object} ErrorResponse and docs/swagger regenerated.

Fixes #76

andrew added 2 commits May 3, 2026 09:33
API handlers returned errors via http.Error (text/plain) with ad-hoc
strings, while the mirror API used a different {"error": "..."} shape
and leaked internal err.Error() text to clients.

Add ErrorResponse{Code, Message} with stable codes (BAD_REQUEST,
NOT_FOUND, UPSTREAM_ERROR, INTERNAL_ERROR) and writeError/badRequest/
notFound/internalError helpers. Convert all JSON API handlers in
api.go, browse.go, mirror_api.go and the /stats endpoint. Enrichment
failures now report 502 UPSTREAM_ERROR rather than 500.

Protocol handlers in internal/handler/ are deliberately unchanged
since npm/pip/cargo clients expect their own response formats, not
JSON. HTML page handlers in server.go also keep text/plain.

Swagger @failure annotations updated and docs regenerated.

Fixes #76
@andrew andrew force-pushed the structured-errors branch from 4306f9e to 768fcec Compare May 3, 2026 08:35
@andrew andrew merged commit 8d27406 into main May 3, 2026
5 checks passed
@andrew andrew deleted the structured-errors branch May 3, 2026 08:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Structured error responses with error codes

1 participant