背景
- 快速
- json 架构
- jv
问题
当我将 setErrorHandler 添加到我的项目/index.js 时,它不起作用。
require('module-alias/register')
const Fastify = require('fastify')
const PORT = process.env.PORT || 3000
const sequelize = require('./orm')
const swagger = require('./config').swagger
const localize = require('ajv-i18n')
const app = Fastify({
logger: {
prettyPrint: true
},
ajv: {
customOptions: {allErrors: true, jsonPointers: true },
plugins: [
require('ajv-errors')
]
}
})
app.register(require('fastify-sensible'))
app.register(require('fastify-swagger'), swagger)
app.register(require('./plugin/systemlogs'))
app.register(require('./plugin/authenticate')).then(()=>{
const routes = require('./routes')
routes(app).forEach((route, index) => {
app.route(route)
})
})
app.setErrorHandler((error,request,reply)=>{
if (error.validation) {
localize.ru(error.validation)
reply.status(400).send(error.validation)
return
}
reply.send(error)
})
const start = async () => {
try {
await sequelize.sync({})
app.log.info('database sync correctly')
await app.listen(PORT, '0.0.0.0')
app.swagger()
} catch (err) {
app.log.error(err)
process.exit(1)
}
}
start()
问题
我想用 ajv i18n 将错误转为中文,我该怎么办?我这样做但不起作用 如何在 fastify 中使用 ajv-i18n ? 我应该在哪里添加 setErrorHandler?
最佳答案
还有另一种方法可以解决这个问题。
谢谢:
- L2jLiga https://github.com/L2jLiga
- 曼努埃尔·斯皮戈隆 网址:
- https://github.com/fastify/help/issues/317
这是另一种方式:
const fastify = require('fastify')
const localize = require('ajv-i18n')
const app = fastify({
ajv: {
customOptions: { allErrors: true, jsonPointers: true },
plugins: [
require('ajv-errors')
]
},
schemaErrorFormatter: (errors, dataVar) => {
localize.ru(errors);
const myErrorMessage = errors.map(error => error.message.trim()).join(', ');
return new Error(myErrorMessage)
}
})
app.get('/', {
schema: {
querystring: {
type: "object",
properties: { a: { type: "string", nullable: false } },
required: ["a"],
},
},
}, async function (req, res) {})
app.listen(3000)
以及响应示例:
{
"statusCode": 400,
"error": "Bad Request",
"message": "должно иметь обязательное поле a"
}
关于ajv - 如何在 fastify 中使用 ajv-i18n ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64922313/