首页 > 解决方案 > Fastify - 自定义错误处理程序中的 i18next

问题描述

在我的 Node.js 应用程序中,我使用 fastify 作为框架以及一些插件(i18next)。我正在使用 i18next 进行翻译(在 preHandler 和处理程序挂钩中正常工作)并希望通过在我的自定义错误处理程序中通过 i18next 使用我的翻译来自定义所有错误(通过 fastify setErrorHandler 方法)。

到目前为止,这是我的编码(从上到下):

import fastify from "fastify";
import routes from "./routes/routes.js";


import i18next from "./config/i18next.js";
import i18nextMiddleware from "i18next-http-middleware";

const app = fastify({
    logger: true,
    ajv: {
        customOptions: {
            allErrors: true,
            $data: true
        }
    },
});

app.register(i18nextMiddleware.plugin, { i18next });

app.register(routes, { prefix: '/api/v1' });

app.setErrorHandler((error, request, reply) => {
    console.log('request.t: ', request.t);
    if (error.validation) {
        // other coding ...
        reply.send(error);
    }
});

(async () => {
    try {
        await app.listen(process.env.PORT);
        console.log(`Server started listening on port ${process.env.PORT}`);
    } catch (err) {
        app.log.error(err);
    }
})();

在 setErrorHandler (同步)内部,我想使用从 i18next 实例传递给请求对象的初始化 t() 方法(这适用于我在 preHandler 和处理程序挂钩中的所有路由)但在 setErrorHandler 中不起作用,因为我发生错误时会变得未定义。我知道 setErrorHandler 是同步的,所有插件注册都将异步处理,但还没有解决。

我还尝试过在注册 i18next 插件时在 after() 挂钩中调用 setErrorHandler,但结果是一样的。我知道我遗漏了一个小细节,但是任何提示都值得赞赏,因为我从几个小时以来就一直在转头。

标签: node.jsi18nextfastify

解决方案


发生这种情况是因为i18next-http-middleware插件将该t方法添加到在 JSON 验证步骤之后执行的钩子request上的对象:preHandler

export function plugin (instance, options, next) {
  const middleware = handle(options.i18next, options)
  instance.addHook('preHandler', (request, reply, next) => middleware(request, reply, next))
  return next()
}

资源

您应该能够编写这样的解决方法:

import i18nextMiddleware from "i18next-http-middleware";

// ....

const middleware = i18nextMiddleware.handle({})
app.addHook('preValidation', (request, reply, next) => middleware(request, reply, next))

我认为这是模块的错误


推荐阅读