Fix UnboundLocalError in ZhipuTranslator error handler

Author: pamod-madubashanaCreated Sep 23, 2026Updated Sep 23, 2026

Description

I hit an UnboundLocalError when translating with the Zhipu service and the API returns an error. In pdf2zh/translator.py:626, ZhipuTranslator.do_translate references response inside the except openai.BadRequestError handler, but response is only assigned when self.client.chat.completions.create() succeeds -- that is, exactly when the handler is not running. So any API-level failure masks the real error with UnboundLocalError: cannot access local variable 'response' ..., and the intended "IRREPARABLE TRANSLATION ERROR" fallback for code 1301 can never trigger.

Reproduce

  1. Build a ZhipuTranslator with a client whose create() raises openai.BadRequestError:
python
from unittest.mock import MagicMock
import openai
from pdf2zh.translator import ZhipuTranslator

t = ZhipuTranslator("en", "zh", None, envs={"ZHIPU_API_KEY": "x", "ZHIPU_MODEL": "glm-4-flash"})
err = openai.BadRequestError.__new__(openai.BadRequestError)
t.client.chat.completions.create = MagicMock(side_effect=err)
t.do_translate("hello")
  1. Observed: UnboundLocalError: cannot access local variable 'response' where it is not associated with a value instead of the original BadRequestError (I confirmed this end to end with an offline stubbed run that raises BadRequestError from create() and calls do_translate).

Expected

The handler should parse the error code from the exception object (e, e.g. via e.body/e.response) instead of the unbound response, so the 1301 case returns "IRREPARABLE TRANSLATION ERROR" and other API errors re-raise as the original BadRequestError. The smallest fix is confined to ZhipuTranslator.do_translate.

Checklist

  • Searched 8 open issues -- no Zhipu error-handler report; closest BadRequestError hit is 使用qwen3报错 #972, a closed qwen3 provider-compat report on a different code path
  • File:line + repro provided

Distinct from 使用qwen3报错 #972: that issue is about the qwen3 provider not being OpenAI-compatible (raised inside OpenAITranslator.do_translate), while this is about the except block in ZhipuTranslator.do_translate referencing an unbound local.

Source: PDFMathTranslate/PDFMathTranslate