Skip to content

Commit

Permalink
Fix: Serialization errors will be send to errorHandler (#3674)
Browse files Browse the repository at this point in the history
  • Loading branch information
int1ch committed Feb 1, 2022
1 parent 17a4875 commit 7cdc903
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 6 deletions.
22 changes: 16 additions & 6 deletions lib/reply.js
Expand Up @@ -365,19 +365,29 @@ function preserializeHookEnd (err, request, reply, payload) {
return
}

if (reply[kReplySerializer] !== null) {
payload = reply[kReplySerializer](payload)
} else if (reply.context && reply.context[kReplySerializerDefault]) {
payload = reply.context[kReplySerializerDefault](payload, reply.raw.statusCode)
} else {
payload = serialize(reply.context, payload, reply.raw.statusCode)
try {
if (reply[kReplySerializer] !== null) {
payload = reply[kReplySerializer](payload)
} else if (reply.context && reply.context[kReplySerializerDefault]) {
payload = reply.context[kReplySerializerDefault](payload, reply.raw.statusCode)
} else {
payload = serialize(reply.context, payload, reply.raw.statusCode)
}
} catch (e) {
wrapSeralizationError(e, reply)
onErrorHook(reply, e)
return
}

flatstr(payload)

onSendHook(reply, payload)
}

function wrapSeralizationError (error, reply) {
error.serialization = reply.context.config
}

function onSendHook (reply, payload) {
if (reply.context.onSend !== null) {
reply[kReplySent] = true
Expand Down
41 changes: 41 additions & 0 deletions test/schema-serialization.test.js
Expand Up @@ -670,3 +670,44 @@ test('error in custom schema serialize compiler, throw FST_ERR_SCH_SERIALIZATION
t.equal(err.code, 'FST_ERR_SCH_SERIALIZATION_BUILD')
})
})

test('Errors in searilizer sended to errorHandler', async t => {
let savedError

const fastify = Fastify()
fastify.get('/', {
schema: {
response: {
200: {
type: 'object',
properties: {
name: { type: 'string' },
power: { type: 'string' }
},
required: ['name']
}
}
}

}, function (req, reply) {
reply.code(200).send({ no: 'thing' })
})
fastify.setErrorHandler((error, request, reply) => {
savedError = error
reply.code(500).send(error)
})

const res = await fastify.inject('/')

t.equal(res.statusCode, 500)

// t.same(savedError, new Error('"name" is required!'));
t.same(res.json(), {
statusCode: 500,
error: 'Internal Server Error',
message: '"name" is required!'
})
t.ok(savedError, 'error presents')
t.ok(savedError.serialization, 'Serialization sign presents')
t.end()
})

0 comments on commit 7cdc903

Please sign in to comment.