Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to disable custom errors #16

Merged
merged 3 commits into from
Dec 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ const [err, user] = await fastify.to(
#### Custom error handler
This plugins also adds a custom error handler which hides the error message in case of `500` errors, instead it returns `Something went wrong`.<br>
This is especially useful if you are using *async* routes, where every uncaught error will be sent back to the user *(but dot not worry, the original error message is logged as error in any case)*.
If needed, it can be disabled by setting the option `errorHandler` to `false`.

## Contributing
Do you feel there is some utility that *everyone can agree on* which is not present?<br>
Expand Down
18 changes: 10 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,16 @@ function fastifySensible (fastify, opts, next) {
})
})

fastify.setErrorHandler(function (error, request, reply) {
if (reply.res.statusCode === 500) {
request.log.error(error)
reply.send(new Error('Something went wrong'))
} else {
reply.send(error)
}
})
if (opts.errorHandler !== false) {
fastify.setErrorHandler(function (error, request, reply) {
if (reply.res.statusCode === 500) {
request.log.error(error)
reply.send(new Error('Something went wrong'))
} else {
reply.send(error)
}
})
}

function to (promise) {
return promise.then(data => [null, data], err => [err, undefined])
Expand Down
24 changes: 24 additions & 0 deletions test/errorHandler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,30 @@ test('The custom error handler should hide the error message for 500s', t => {
})
})

test('The custom error handler can be disabled', t => {
t.plan(3)

const fastify = Fastify()
fastify.register(Sensible, { errorHandler: false })

fastify.get('/', (req, reply) => {
reply.send(new Error('kaboom'))
})

fastify.inject({
method: 'GET',
url: '/'
}, (err, res) => {
t.error(err)
t.strictEqual(res.statusCode, 500)
t.deepEqual(JSON.parse(res.payload), {
error: 'Internal Server Error',
message: 'kaboom',
statusCode: 500
})
})
})

test('The custom error handler should hide the error message for 500s (promise)', t => {
t.plan(3)

Expand Down