Extend support for Express middlewares to include error handling #674
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The kind of change this PR does introduce
Current behaviour
Currently, the next function passed to express-style middlewares does not take into account any potential errors handed to it. If a express-style middleware fails, the connection and all following middlewares will still be executed and a connection will be established successfully.
New behaviour
If any value other than undefined is passed to the next function, all further middlewares will not be executed. The socket will be closed, receiving an error "Bad Request" as if the verify function in server.ts had failed. This behaviour is more consistent with how express handles errors emerging in its middleware (see here for details).
Other information (e.g. related issues)
I mostly wrote the code for this pull request to see if there was any obvious obstacles with handling errors as described above. I had recently found myself in a situation where I wanted to verify CSRF tokens during connection establishment but was unable to fail connection attempts from within middlewares.
Obviously, there may be things I have missed or possibly even good reasons to not allow any such error handling at all. If there are, please dismiss this pull request. Additionally, it may be more advantageous to return a custom, new type of error or possibly to not return a 'middleware failure' token in the error context out of security considerations.
I have added two tests for failing middlewares (both polling and websockets).
Thank you for your time!