Module iron::middleware
[−]
[src]
Iron's Middleware and Handler System
Iron's Middleware system is best modeled with a diagram.
[b] = BeforeMiddleware
[a] = AfterMiddleware
[[h]] = AroundMiddleware
[h] = Handler
With no errors, the flow looks like:
[b] -> [b] -> [b] -> [[[[h]]]] -> [a] -> [a] -> [a] -> [a]
A request first travels through all BeforeMiddleware, then a Response is generated by the Handler, which can be an arbitrary nesting of AroundMiddleware, then all AfterMiddleware are called with both the Request and Response. After all AfterMiddleware have been fired, the response is written back to the client.
Iron's error handling system is pragmatic and focuses on tracking two pieces of information for error receivers (other middleware):
- The cause of the error
- The result (what to do about) the error.
The cause of the error is represented simply by the error itself, and the result of the error, representing the action to take in response to the error, is a complete Response, which will be sent at the end of the error flow.
When an error is thrown in Iron by any middleware or handler returning an Err
variant with an IronError
, the flow of the Request switches to the error flow,
which proceeds to just call the catch
method of middleware and sidesteps the
Handler
entirely, since there is already a Response in the error.
A Request can exit the error flow by returning an Ok from any of the catch methods. This resumes the flow at the middleware immediately following the middleware which handled the error. It is impossible to "go back" to an earlier middleware that was skipped.
Generally speaking, returning a 5XX error code means that the error flow should be entered by raising an explicit error. Dealing with 4XX errors is trickier, since the server may not want to recognize an error that is entirely the clients fault; handling of 4XX error codes is up to to each application and middleware author.
Middleware authors should be cognizant that their middleware may be skipped during
the error flow. Anything that must be done to each Request or Response should
be run during both the normal and error flow by implementing the catch
method to
also do the necessary action.
Structs
Chain |
The middleware chain used in Iron. |
Traits
AfterMiddleware |
|
AroundMiddleware |
AroundMiddleware are used to wrap and replace the |
BeforeMiddleware |
|
Handler |
|