fastify / fastify-sensible

Defaults for Fastify that everyone can agree on

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fastify.error()

franciscolourenco opened this issue · comments

🚀 Feature Proposal

It is harder to remember and type https status codes names, compared to numbers:

throw fastify.httpErrors.unauthorized('Incorrect password')

On the other hand the assert api is easy to read and write:

fastify.assert(false, 401, 'Incorrect password')

The proposal is to expose an error api to generate errors by status code.

fastify.error(401, 'Incorrect password')

or

throw fastify.error(401, 'Incorrect password')

Motivation

Make the error interface easier to use and more similar to fastify.assert()

Example

fastify.error(401, 'Incorrect password')

Fair point! Would you like to send a pr?

I'm not sure if I have the time but I can try.

I'm wondering if the error should be thrown automatically or not. On one hand throwing automatically would be more succinct and similar to assert().On the other hand, having to throw the error is more explicit.

Is there any situation where would would like to create an error but not throw it?

Is there any situation where would would like to create an error but not throw it?

If the handler is sync and not async, the throw would lead to a server crash.

So an error factory let the user choose what to do: throw the error or just return it: reply.code(123).send(fastify.error(401, 'Incorrect password'))

I suppose assert() handles sync without throwing an error?

Reading the docs it doesn't:

Verify if a given condition is true, if not it throws the specified http error.
Very useful if you work with async routes.

assert() can't know if it is in an async or sync context.
I think this API has been designed as the standard nodejs assert.
I think this API (fastify.error) has a different purpose vs the assert one

It is like this example for my point of view:

const notFoundErr = fastify.httpErrors.notFound('custom message')

const notFoundErr = fastify.error(404, 'Cannot find user xyz')

Do you agree?

The .error behavior should be the same as the .httpErrors.*, it's just a shorthand alias.

commented

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Merged in #38