Skip to content

Commit 3f099d1

Browse files
authored
fix(service): return 500 instead of crashing on translation error (#224)
The /translate, /v1/translate and /v2/translate handlers called log.Fatalf when TranslateByDeepLX returned an error. log.Fatalf calls os.Exit, so a single failed translation would tear down the whole server process. Return a 500 JSON response and keep serving instead.
1 parent 1b88e42 commit 3f099d1

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

service/service.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,11 @@ func Router(cfg *Config) *gin.Engine {
127127

128128
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
129129
if err != nil {
130-
log.Fatalf("Translation failed: %s", err)
130+
c.JSON(http.StatusInternalServerError, gin.H{
131+
"code": http.StatusInternalServerError,
132+
"message": "Translation failed: " + err.Error(),
133+
})
134+
return
131135
}
132136

133137
if result.Code == http.StatusOK {
@@ -191,7 +195,11 @@ func Router(cfg *Config) *gin.Engine {
191195

192196
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
193197
if err != nil {
194-
log.Fatalf("Translation failed: %s", err)
198+
c.JSON(http.StatusInternalServerError, gin.H{
199+
"code": http.StatusInternalServerError,
200+
"message": "Translation failed: " + err.Error(),
201+
})
202+
return
195203
}
196204

197205
if result.Code == http.StatusOK {
@@ -243,7 +251,11 @@ func Router(cfg *Config) *gin.Engine {
243251

244252
result, err := translate.TranslateByDeepLX("", targetLang, translateText, "", proxyURL, "")
245253
if err != nil {
246-
log.Fatalf("Translation failed: %s", err)
254+
c.JSON(http.StatusInternalServerError, gin.H{
255+
"code": http.StatusInternalServerError,
256+
"message": "Translation failed: " + err.Error(),
257+
})
258+
return
247259
}
248260

249261
if result.Code == http.StatusOK {

0 commit comments

Comments
 (0)