Repository navigation
Return one HTTPError with the server's code and message from both clients - #36
DzmitryHumianiuk wants to merge 6 commits into
Conversation
…ents
A failed call through the generated client reported only the HTTP status
("404 Not Found"), or a oneOf decoding error instead of the status for a
rejected API key, while the Resty clients dumped the raw body.
gorp.HTTPError now carries the status, request, ReportPortal error code and
message, OAuth error and the raw body. Both clients build it with the same
tolerant parser: the generated client through Configuration.ResponseMiddleware
(all operations, declared status or not), the Resty clients through their
response handler. Errors of the generated client still unwrap to
*openapi.GenericOpenAPIError. errors.Is works with ErrUnauthorized,
ErrForbidden, ErrNotFound and ErrNotAPIResponse.
The Resty clients now fail on a 2xx text/html response (wrong host or path)
instead of returning an empty result.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A token request of WithPasswordOwnerGrantAuth fails inside the OAuth2 transport, before any API response exists, so neither client's response handling saw it and the caller got the oauth2 package's two-line text. The token source now converts *oauth2.RetrieveError into the same HTTPError as a failed API call: request (the token endpoint), status, OAuth error and description, or ReportPortal's error code and message (ReportPortal 6 answers a wrong password with an ErrorRS body). HTTPError.Unwrap returns the RetrieveError, so errors.As to it keeps working. A token "error" answered with status 200 is not mistaken for an HTML page: the 2xx HTML case moved out of newHTTPError into newNotAPIError. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The generated client has a single ResponseMiddleware slot, read from the Configuration on every call, so a middleware assigned by the user silently replaced OpenAPIErrorMiddleware and brought the generated error texts back. ChainResponseMiddleware combines middlewares into one: they run in the given order, nil entries are skipped, the first error wins. With the user's middleware first it sees failed responses too and the call still returns an HTTPError. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…tions A wrong host or base path lands on the UI or a login page, which answers 200 with HTML. The Resty clients already report that as ErrNotAPIResponse; the generated client failed with "undefined response type", because its middleware could not tell a JSON operation from one that legitimately returns a file or an HTML report. OpenAPIErrorMiddleware now matches the answered request (method + path template, compared with the end of the path) against nonJSONOperations and returns ErrNotAPIResponse for a 2xx text/html response of any other operation. The list is derived from pkg/openapi/api/openapi.yaml: the 41 operations with no application/json content in a 2xx response, or with that content declared as a binary string. A test recomputes it from the YAML and prints the list to paste when it drifts; another one checks that no JSON operation's path fits an exempt template. go.yaml.in/yaml/v3 becomes a direct (test-only) dependency; it was already in go.sum through testify. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
README "Errors": how to keep OpenAPIErrorMiddleware next to a middleware of your own, which operations are exempt from the HTML check, what a failed password-grant token request looks like. AGENTS.md: file table row for nonjson_operations.go and the rule to update the list after regenerating the client. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The oauth2 package reads the "error" field of any JSON body into
RetrieveError.ErrorCode. For a wrong token URL answered by Spring's
default handler ({"status":404,"error":"Not Found","path":…}) the
fallback in newTokenError copied it, and the text became
"404 Not Found: Not Found" instead of the "no such endpoint" hint.
The fallback now applies only to a body that is not a JSON object,
the form-encoded case it exists for. README: the status sentinels
match a token failure as well.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Follow-up: the three gaps listed in the description are closedFive new commits on top of fec2325, no force-push:
Live ReportPortal 6 server,
The leading Changes
Behaviour change for library users
Verification
Investigation log
Harness (run as
|
|
Local ReportPortal 6.0.0 check (same build as demo): the prepared probe ran. It created a |
Summary
Fixes #35. Depends on #33 (stacked on
fix/openapi-errorcode-integer;ErrorRS.errorCodeisint64there, which the error model in this PR relies on).Every failed API call in goRP now returns a
*gorp.HTTPErrorwhose text has the request, the HTTP status and what the server said, and which works witherrors.Asanderrors.Is. This applies to the Resty-based clients and to all 358 operations of the generated client, without regeneratingpkg/openapi.Live ReportPortal 6 server, read-only GETs,
err.Error()before and after:data failed to match schemas in oneOf(SaveAnalyticsSettings1401Response): json: cannot unmarshal object into Go value of type stringGET https://<host>/api/v1/<project>/launch: 401 Unauthorized: invalid_token: Invalid access tokenstatus code error: 401\n{\n "error_description" : "Invalid access token",\n "error" : "invalid_token"\n}404 Not FoundGET https://<host>/api/v1/<project>/launch/999999999: 404 Not Found: Launch '999999999' not found. Did you use correct Launch ID? (error code 4041)status code error: 404\n{"errorCode":4040,"message":"Project 'no-such-project-gorp' not found. Did you use correct project name?"}GET https://<host>/api/v1/no-such-project-gorp/launch: 404 Not Found: Project 'no-such-project-gorp' not found. Did you use correct project name? (error code 4040)400 Bad RequestGET https://<host>/api/v1/<project>/launch: 400 Bad Request: Sorting parameter noSuchField is not defined (error code 40012)status code error: 400\n{"errorCode":40012,"message":"Sorting parameter noSuchField is not defined"}/nosuchservice), Resty<nil>, 0 launchesGET https://<host>/nosuchservice/api/v1/<project>/launch: 200 OK: expected JSON but got an HTML page, the host or path is probably not the ReportPortal APICLI after (before: see the issue):
Changes
pkg/gorp/errors.go(new):HTTPErrormoved here fromclient.goand extended.StatusCodeandResponse(raw body) keep their meaning.Status,Method,URL,ErrorCode(ReportPortal code, e.g. 4041),Message,OAuthError.Error()is one line:<METHOD> <URL without query>: <status>: <message> (error code N). Without a recognizable message it appends the body with whitespace collapsed and cut to 1024 bytes.Unwrap()returns a*openapi.GenericOpenAPIErroron the generated-client path.Is()supports the new sentinelsErrUnauthorized(401),ErrForbidden(403),ErrNotFound(404),ErrNotAPIResponse(2xx HTML).newHTTPError, handles every body shape listed in the issue and never fails; unknown shapes fall back to the raw body.OpenAPIErrorMiddleware(exported) is set asConfiguration.ResponseMiddlewareinnewAPIClient. The generatedExecutefunctions call the middleware before their own status handling, so it covers undeclared statuses and the 401 OAuth body that the generatedoneOfcan't decode. It also rejects a 2xxtext/htmlresponse, except for the 41 operations that don't return JSON (pkg/gorp/nonjson_operations.go, derived from the specification and checked against it by a test).ChainResponseMiddleware(exported) combines a user's response middleware withOpenAPIErrorMiddlewarein the generated client's single middleware slot.defaultHTTPErrorHandler(Resty) builds the same error, and now also rejects a 2xx response withtext/html/application/xhtml+xml.pkg/gorp/oauth2.go: a failed token request ofWithPasswordOwnerGrantAuthis converted into the sameHTTPError, which unwraps to*oauth2.RetrieveError.scripts/openapi-compat/compat.go.tmpl→pkg/openapi/compat.go:NewGenericOpenAPIError(status, body, model). The fields ofGenericOpenAPIErrorare unexported, so this is the only way to keeperrors.As(err, &genericErr)working. No generated file is touched.pkg/gorp/errors_test.go): 11 response shapes × both clients againsthttptest, the 2xx HTML case on both Resty clients, the generated client's 2xx HTML check and its exemptions, the list of exempt operations recomputed from the specification, token failures of the password grant on all three callers, middleware chaining, error text details. The tests from openapi: decode ErrorRS.errorCode as an integer #33 (openapi_errors_test.go) and the existingHTTPErrortest pass unchanged.README.md: "Errors" section in the library part.AGENTS.md: file table row and a design note.Behaviour change for library users
*gorp.HTTPError.errors.As(err, &genericErr)with*openapi.GenericOpenAPIErrorkeeps working.Body()is the raw body andError()of the unwrapped value is the status line.Model()is now anErrorRSvalue whenever the body is a ReportPortal error, for any status. Before, it was set only for statuses the spec declares. It isnilfor other bodies; before, a Spring default body on a declared status gave an emptyErrorRS, and a 401 gave a decode error.err.(*openapi.GenericOpenAPIError)no longer matches. Useerrors.As.*http.Responsereturned next to the error is unchanged.status code error: <code>\n<raw body>. It is now one line with the request, status and message. The numeric status and the server's message are still in the text; the raw JSON is only inHTTPError.Response. Code that matches on the old text breaks.HTTPErrorhas new fields. Keyed literals and field access compile as before; an unkeyed literalHTTPError{404, "x"}doesn't.text/htmlresponse is now an error on both clients (errors.Is(err, gorp.ErrNotAPIResponse)), not an empty result (Resty) orundefined response type(generated).GetLaunchReport,GetFile,GetPublicFile,ExportProjects,DownloadAttachment, deletes that return nothing, …). They are recognised by the method and path of the answered request.Content-Typeis checked. A page served without it, or astext/plain, still fails in the generated decoder as before.WithPasswordOwnerGrantAuthis anHTTPErrortoo. Text:failed to fetch token: POST <token URL>: <status>: <server's message>. The sentinels match it as well, soerrors.Is(err, gorp.ErrNotFound)can mean a wrong token URL;HTTPError.URLtells which request failed.errors.Asto*oauth2.RetrieveErrorkeeps working; the old textoauth2: cannot fetch token: …is gone.ResponseMiddlewarestill replacesOpenAPIErrorMiddleware, because the generated client reads that field on every call. Keep both withcfg.ResponseMiddleware = gorp.ChainResponseMiddleware(yours, gorp.OpenAPIErrorMiddleware). Middlewares run in the given order and the first error is returned.errors.Is(err, gorp.ErrNotFound)is true for any 404, including a wrong path answered by Spring's default handler.ErrorCode != 0tells a ReportPortal "entity not found" from a wrong endpoint.HTTPError.URLhas the full URL with any userinfo password redacted.Not covered
HTTPError.*url.Errortext thatnet/httpputs in front of a token failure (Get "<API URL with query>": …) contains the query string of the API request. goRP strips the query only from its own part of the text./api/sso/oauth/token; the/uat/sso/oauth/tokenURL used inpkg/gorp/reporting_flow_test.go:257answers 405 on the live ReportPortal 6 server. goRP takes the token URL from the caller'soauth2.Config, so nothing in the library is wrong, but any documentation that names the/uatURL is out of date for ReportPortal 6.Merge note: #34 also edits
scripts/openapi-compat/compat.go.tmpl. This PR only appends one function at the end of the file, so the conflict, if any, is trivial.Verification
go build ./...,go vet ./...,go vet -tags e2e ./e2e/...: cleango test -race -count=1 -cover ./...: pass (pkg/gorp95.2 %, was 94.7 % on fec2325;internal/commands77.5 %)go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./...: 0 issues (the pinned version, run without Docker)task e2e(writes to the server),task generate-openapi-client(needs Docker; not needed,compat.gowas re-copied from the template withcpanddiffshows them identical)Investigation log
Reproduce the problem on the base branch.
git checkout -b fix/api-errors origin/fix/openapi-errorcode-integer(5a832e4). A small program (below) calls both clients with read-only GETs and printserr.Error(); a script (below) runs the CLI. Both were run on 5a832e4 (git checkout --detach 5a832e4) and on this commit; the outputs are the before/after tables. This confirmed first-hand: the oneOf text for 401, status-only for 404/400 on the generated client, the raw dump on Resty,nilfor a 200 HTML page on Resty, and the CLI texts. Spec counts:jq '[.paths[][] | objects | .responses?["401"]?.content? // {} | .[]?.schema | select(.oneOf != null) | [.oneOf[] | (.["$ref"] // .type)] | sort | join(",")] | group_by(.) | map({k: .[0], n: length})' reportportal-api-docs.json→ one group,…ErrorRS,string, n = 282;grep -c 'StatusCode == 404' pkg/openapi/api_launch.go→ 0;grep -h -c 'StatusCode == 404' pkg/openapi/api_*.go | awk '{s+=$1} END{print s}'→ 54.Library harness (run as
go run ./internal/zzlivewithRP_ENDPOINT,RP_PROJECT,RP_API_KEYset; not committed)CLI script
Why the generated client shows only the status.
pkg/openapi/client.go:779(Error()returnse.error),:794(formatErrorMessagereads onlyTitle/Detail). The 401 branch decodes intoSaveAnalyticsSettings1401Responseand puts the decode error into the text:pkg/openapi/api_launch.go:3246-3256.Which hook exists.
pkg/openapi/configuration.go:84,98:ResponseMiddleware func(*http.Response, []byte) error. EveryExecutecalls it after reading the body and before theStatusCode >= 300branch, and returns its error together with the response:pkg/openapi/api_launch.go:3234-3239. Counted:grep -c "cfg.ResponseMiddleware(" pkg/openapi/api_*.gosums to 358, same asgrep -c "Execute(r ". So one middleware covers all operations, declared status or not, with no regeneration.newAPIClient(pkg/gorp/client.go) did not set it.Extend
HTTPError, no second type.HTTPError{StatusCode, Response}was already exported and matched witherrors.Asinpkg/gorp/reporting_flow_test.go:217. New fields are additive. The old test passes unchanged.Keeping
errors.As(err, *openapi.GenericOpenAPIError). openapi: decode ErrorRS.errorCode as an integer #33's test (pkg/gorp/openapi_errors_test.go:110-124) relies on it, includingBody(), the status in the text andModel()as anErrorRSvalue. The struct fields are unexported (client.go:772-776), so a constructor has to live in packageopenapi. The only hand-written file there iscompat.go, sourced fromscripts/openapi-compat/compat.go.tmpl(Taskfile.yml:94copies it). AddedNewGenericOpenAPIErrorto the template and re-copied withcp;diff scripts/openapi-compat/compat.go.tmpl pkg/openapi/compat.gois empty.HTTPError.Unwrap()returns it. openapi: decode ErrorRS.errorCode as an integer #33's test passes unmodified.Model()semantics. Set only when the body haserrorCode(or a baremessage) and decodes into the generatedErrorRS;nilfor OAuth, Spring default and non-JSON bodies. This removes the "empty non-nil model" trap for the Spring body.errorCodeis read throughjson.RawMessage, so a string code still fillsHTTPError.ErrorCodealthough the generated model (int64 after openapi: decode ErrorRS.errorCode as an integer #33) can't hold it; the test case "ErrorRS with the code as a string" covers that.Telling the JSON shapes apart.
erroris a string in both the OAuth and the Spring default body. OAuth is recognised byerror_description, or byerrorwithoutstatus/path; Spring default bystatuspluspathortimestamp. The Spring body only repeats the status and path, so for a 404 the text gets the hint "no such endpoint, check the host and the path"; other statuses fall back to the raw body. The hint is not stored inMessage, which holds only what the server said.Empty 401. The reason is only in
WWW-Authenticate;erroranderror_descriptionparameters are extracted with a regexp intoOAuthError/Message, otherwise the header is shown in the text as is (as a hint, not inMessage).Resty side.
resty.dev/v3@v3.0.0-rc.4/middleware.go:545-590(MiddlewareResponseAutoParse): for a JSON 4xx without a registered error type the body is not consumed, and for an unknown content type it is read withreadAll;response.go:149-151,258-262(Bytes()→readIfRequired). So the handler can read the body in every case; the tests checkHTTPError.Responseequals the sent body for JSON, text, HTML and empty bodies. The handler error is returned by the request throughclient.go:2569-2575.2xx HTML: Resty only. Every Resty call in
pkg/gorpusesSetResultwith a JSON model (grep -n "SetResult" pkg/gorp/*.go), so HTML is never valid there. For the generated client I listed theExecutefunctions that send onlyAccept: application/jsonbut return no model:awk '/^func \(a \*[A-Za-z]+\) [A-Za-z0-9]+Execute\(/{sig=$0} /localVarHTTPHeaderAccepts := \[\]string\{"application\/json"\}$/{print sig}' pkg/openapi/api_*.go | grep -v "Execute(r [A-Za-z0-9]*) (\*\?[A-Z\[m]". Among them:GetLaunchReportExecute,GetFileExecute,GetPublicFileExecute,ExportProjectsExecute,DownloadAttachmentExecute(*os.File) and others. A middleware sees only the response, so a blanket HTML check would break report and attachment downloads. Left as is and covered byTestOpenAPIErrorMiddlewareLeavesSuccessAlone. Superseded: see the follow-up comment, the middleware now matches the request against the operations that don't return JSON.Status threshold. The middleware acts from 300 up, matching the generated code (
api_launch.go:3241). The Resty handler keeps its previous threshold of 400 (IsStatusFailure).CLI unaffected in logic.
grep -rn "StatusCode" internal/commands/*.gofinds onlyquality_gate.go:201(isPermanentHTTPStatusreads the*http.Response, which is still returned).e2e/e2e_helpers_test.go:213-225also readsresp.StatusCode. CLI output only gains the better text.Password grant.
pkg/gorp/oauth2.go:21-25: a failed token request returns fromToken()inside the OAuth2 transport, so no API response reaches either handler. Out of scope here. Superseded: see the follow-up comment.Sentinels.
ErrUnauthorized,ErrForbidden,ErrNotFound,ErrNotAPIResponsethroughHTTPError.Is: three lines each and they give both clients one way to test a status. No error-code constants were added.Error text. One line (slog-friendly), request first, query string dropped,
URL.Redacted()for userinfo. Raw body cut at 1024 bytes on a rune boundary only in the text.After. Same program and script on the commit (the "After" outputs). Lint:
go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run ./...→0 issues; formatting with the same binary'sfmton the touched files.🤖 Generated with Claude Code