배경
문제
내 project / index.js에 setErrorHandler를 추가하면 작동하지 않습니다.
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를 어디에 추가해야합니까?
이 문제를 처리하는 다른 방법이 있습니다.
감사:
이것은 또 다른 방법입니다.
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"
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다