# node: 错误处理与回退内容
URL: https://generaltranslation.com/zh/docs/node/guides/error-handling.mdx
---
title: 错误处理与回退内容
description: 没有可用译文时会发生什么,以及如何处理
---
## 默认回退内容行为
当翻译不可用时——无论是区域设置不受支持、翻译文件缺失,还是无法访问 CDN——`gt-node` 都会返回 `defaultLocale` 中的原始字符串。你的应用绝不会因缺少翻译而崩溃。
```js
import { getGT } from 'gt-node';
app.get('/api/greeting', async (req, res) => {
const gt = await getGT();
// 如果西班牙语翻译不可用,返回英语原文
res.json({ message: gt('Hello, world!') });
});
```
这种回退内容是自动处理的。译文缺失时,你不需要用 try/catch 包裹翻译调用。
## 缺少的区域设置
如果请求的区域设置尚未在 `locales` 中配置,翻译函数会回退到 `defaultLocale`:
```js
initializeGT({
defaultLocale: 'en',
locales: ['en', 'es', 'fr'], // 未包含日语
});
// 使用 Accept-Language: ja 的请求
// gt('Hello!') → 返回 'Hello!'(英语回退内容)
```
要支持新的区域设置,请将其添加到 `locales` 数组中,然后重新生成译文:
```bash
npx gt translate
```
## 检查可用区域设置
使用 [`getLocales()`](/docs/node/api/get-locales) 和 [`getDefaultLocale()`](/docs/node/api/get-default-locale) 查看 runtime 中有哪些可用的区域设置:
```js
import { getLocales, getDefaultLocale } from 'gt-node';
app.get('/api/locales', (req, res) => {
res.json({
supported: getLocales(),
default: getDefaultLocale(),
});
});
```
## 处理 API 响应中的翻译
开发 API 时,您可能希望在内容采用回退内容语言时明确标明:
```js
import { getGT, getLocale, getDefaultLocale } from 'gt-node';
app.get('/api/greeting', async (req, res) => {
const gt = await getGT();
const locale = getLocale();
const defaultLocale = getDefaultLocale();
res.json({
message: gt('Hello, world!'),
locale,
isFallback: locale !== defaultLocale,
});
});
```
## 调试翻译
### 检查当前激活的区域设置
```js
import { getLocale } from 'gt-node';
app.use((req, res, next) => {
console.log(`[i18n] Request locale: ${getLocale()}`);
next();
});
```
### 验证译文是否已加载
在开发环境中,`gt-node` 会通过 API 按需 (on-demand) 翻译。如果看起来缺少译文:
1. 确认已设置 `GT_API_KEY` 和 `GT_PROJECT_ID`
2. 检查当前区域设置是否在你的 `locales` 数组中
3. 查看服务器日志中是否有错误
### 生产环境检查清单
部署前,请确认:
* [ ] `npx gt translate` 在你的 build 脚本中运行成功
* [ ] 所有目标区域设置都已列在 `gt.config.json` 中
* [ ] 已在生产环境中设置 `GT_PROJECT_ID`
* [ ] 已在生产环境中设置 `GT_API_KEY` (供 `npx gt translate` 使用)
在开发环境中,翻译按 按需 方式进行,因此可能较慢。在生产环境中,务必使用 `npx gt translate` 预先生成译文——参见 [CLI docs](/docs/cli/translate)。
## 后续步骤
* [字符串翻译模式](/docs/node/guides/strings) — 两种翻译方式
* [本地译文存储](/docs/node/guides/local-tx) — 将译文打包到 bundle 中以供离线使用
* [`getLocale` API 参考](/docs/node/api/get-locale)