如何从 Fastify v3 返回自定义错误?

ton*_*ata 2 custom-errors custom-error-handling fastify

如你所知,Fastify 中的默认错误界面如下所示

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Missing property blah-blah"
}
Run Code Online (Sandbox Code Playgroud)

我真的希望能够扔掉类似的东西

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Missing property blah-blah",
    "myCustomError": "yo yo I am custom"
}
Run Code Online (Sandbox Code Playgroud)

setErrorHandler我尝试了使用和 的多种(真的很多!)组合,addHook("onError")但我无法返回任何自定义错误。无论我做什么,我从处理程序内部抛出的自定义错误都会以某种方式转换为这个默认接口,并且无法找到解决方法。我也尝试过使用onSendonResponse钩子。我尝试过的一切都没有成功。:(

Fastify v3 中是否有可能返回自定义错误?如果在 v3 中无法实现,那么 Fastify v4 又如何呢?有人能提供一个在 Fastify 中启用自定义错误的代码设计吗?

Man*_*lon 5

每当您返回/抛出一个 时Error,Fastify 都会使用不包含任何其他属性的默认序列化器来处理它。

为此,您需要列出想要作为输出的字段:

const statusCodes = require('http').STATUS_CODES
const fastify = require('fastify')({ logger: true })

fastify.get('/', async (request, reply) => {
  const err = new Error('hello')
  err.statusCode = 400
  err.myCustomError = 'yo yo I am custom'
  throw err
})

fastify.setErrorHandler(function (error, request, reply) {
  if (error.myCustomError) {
    reply
      .status(error.statusCode || 500)
      .send({
        error: statusCodes[error.statusCode || 500],
        message: error.message,
        myCustomError: error.myCustomError,
        statusCode: error.statusCode || 500
      })
  } else {
    reply.send(error) // fallback to the default serializer
  }
})

// {"error":"Bad Request","message":"hello","myCustomError":"yo yo I am custom","statusCode":400}
fastify.inject('/').then(res => console.log(res.payload))
Run Code Online (Sandbox Code Playgroud)

此代码适用于 fastify v3 和 v4

也考虑阅读这篇文章