diff --git a/lib/reply.js b/lib/reply.js index 50f3e81435..437df87dcc 100644 --- a/lib/reply.js +++ b/lib/reply.js @@ -365,12 +365,18 @@ 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) @@ -378,6 +384,10 @@ function preserializeHookEnd (err, request, reply, 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 diff --git a/test/schema-serialization.test.js b/test/schema-serialization.test.js index 66a3228440..b6794d5340 100644 --- a/test/schema-serialization.test.js +++ b/test/schema-serialization.test.js @@ -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() +})