Skip to content

fix: handle translation API errors instead of panicking - #10

Closed
MrBeldum wants to merge 1 commit into
casdoor:masterfrom
MrBeldum:fix/translator-error-handling
Closed

MrBeldum wants to merge 1 commit into
casdoor:masterfrom
MrBeldum:fix/translator-error-handling

Conversation

@MrBeldum

@MrBeldum MrBeldum commented Oct 5, 2026

Copy link
Copy Markdown

Problem

StrTranslate ignored the error from http.PostForm and then deferred resp.Body.Close(), so any network failure caused a nil pointer dereference. It also read translateResp.Data.Translations[0] before checking translateResp.Error.Code, so when the Google API returned an error response (invalid key, quota exceeded, etc.) the handler panicked with an index-out-of-range error and the Error.Message branch could never run.

go vet flags both the first issue (using resp before checking for errors) and a separate format bug in getGitterAvatarUrl, where username (a string) is printed with %d.

Fix

  • Move the HTTP call into a small googleTranslate helper that returns an error for transport failures, body read failures, invalid JSON, API error responses, and empty translations arrays.
  • StrTranslate now passes those errors back through TranslateData.ErrMsg, the field the frontend already reads, so it no longer panics.
  • Use %s for username in the gitter avatar retry log.

Tests

Added object/translator_test.go, which runs googleTranslate against an httptest server for success, API error, empty result, non-JSON response, and unreachable endpoint cases. These tests don't need a database:

go test ./object/ -run TestGoogleTranslate -v

go vet ./object/ no longer reports either issue.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@hsluoyz

hsluoyz commented Oct 9, 2026

Copy link
Copy Markdown
Member

Thanks for spotting this! Both panics (nil resp on transport errors and the out-of-range Translations[0] on API errors) are real, and so is the %d format bug in the gitter log.

We've fixed it directly in 769a889 with a smaller change that keeps the logic inside StrTranslate. It also adds a request timeout, and the frontend now shows err_msg (it didn't read that field before, so errors would otherwise just show up as an empty translation). We'd rather not add test files to this repo, so closing this PR. Thanks again!

@hsluoyz hsluoyz closed this Oct 9, 2026
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.

3 participants