Appearance
api.service.RoutingErrorHandler 1.3.0
This service is used in defining and processing the configuration of policies and routes to distinguish between handlers meant to commonly process a request and handlers meant to exclusively deal with cases in which a previously invoked handler has failed.
When defining route and policy configuration, this service can be used to tag handlers meant to handle error situations. On dispatching requests, either handler is tested for this tag to decide when to invoke it based on current state of request dispatching.
In configuration, using common module function pattern is necessary to make sure configuration isn't performed prior to having discovered all services properly.
javascript
export function policies() {
const api = this;
return {
"ALL /api": [
( req, res, next ) => { ... },
api.service.RoutingErrorHandler( ( error, req, res, next ) => {
...
} )
]
};
}
javascript
export default function() {
const api = this;
return {
policies: {
"ALL /api": [
( req, res, next ) => { ... },
api.service.RoutingErrorHandler( ( error, req, res, next ) => {
...
} )
]
}
};
}
javascript
export default function() {
const api = this;
return {
policies() {
return {
"ALL /api": [
( req, res, next ) => { ... },
api.service.RoutingErrorHandler( ( error, req, res, next ) => {
...
} )
]
};
}
};
}
In these examples, two policy routes for prefix /api
are declared.
- The first one is invoked unless some error has happened while dispatching the request.
- The second one is invoked iff some error has happened while dispatching the request.
Errors occur in request handlers
- by passing an
Error
as argument to thenext()
callback of a policy's handler, - by throwing an exception or
- by returning a promise which is eventually rejected.
Why is tagging necessary?
This question has been answered here.
Both CMFP-based examples provided above are preferred over the CMP-based one as they make sure that the function for declaring the policies isn't invoked prior to having all services properly exposed.
Static methods
tag()
This method can be used on configuring policies and routes to mark a provided handler to be considered after an error occurred while dispatching a request to deal with that error in a customized way. It takes a function as argument and returns that function covertly tagged for exclusively handling error situations.
See above for examples on how to use it.
isTagged()
This method is used on dispatching requests to configured handlers to distinguish whether some handler is meant to commonly process the request or to deal with some previously invoked handler having failed. It takes a handler to be invoked as argument and returns whether the tag covertly applied during configuration exists on that handler or not.