Skip to content

early response on error instead of proceeding with the lifecycle using next#8

Closed
salmanm wants to merge 2 commits intofastify:masterfrom
salmanm:master
Closed

early response on error instead of proceeding with the lifecycle using next#8
salmanm wants to merge 2 commits intofastify:masterfrom
salmanm:master

Conversation

@salmanm
Copy link
Copy Markdown
Member

@salmanm salmanm commented Apr 1, 2019

No description provided.

Copy link
Copy Markdown
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a unit test? Also I think we should call next(err).

@salmanm
Copy link
Copy Markdown
Member Author

salmanm commented Apr 1, 2019

I think calling next(err) would let it continue the request life cycle and eventually land up in the same situation. Wouldn't it?

@salmanm
Copy link
Copy Markdown
Member Author

salmanm commented Apr 1, 2019

I suppose in this case (missing auth header), we should be doing an early response from the hook. I don't think the control should ever reach the handler. I did test it locally and found it working. (Unless I've missed some case you're thinking)

I'll add a unit test as soon as we come to a conclusion on this.

@mcollina
Copy link
Copy Markdown
Member

mcollina commented Apr 1, 2019

I suppose in this case (missing auth header), we should be doing an early response from the hook. I don't think the control should ever reach the handler. I did test it locally and found it working. (Unless I've missed some case you're thinking)

That's true, right. We shouldn't call next() at all.

@salmanm
Copy link
Copy Markdown
Member Author

salmanm commented Apr 1, 2019

Added a test to ensure the correct response.

Copy link
Copy Markdown
Member

@delvedor delvedor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@salmanm
Copy link
Copy Markdown
Member Author

salmanm commented Apr 2, 2019

https://www.fastify.io/docs/latest/Hooks/#respond-to-a-request-from-a-hook

If needed, you can respond to a request before you reach the route handler.

Isn't this a use case of the above pattern? We're in preHandler and we don't want the life cycle to be continued because user isn't authenticated. If we let it continue, the custom setErrorHandler (if set) kicks in and converts the 401 to 500 response.

@salmanm
Copy link
Copy Markdown
Member Author

salmanm commented Apr 2, 2019

Closing as its fixed in #9

@salmanm salmanm closed this Apr 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants