Appearance
api.service.Response
This service provides responses commonly used as fallback or in case an error occurred and has not been handled by a request handler accordingly.
Static methods
error()
This method is invoked when catching an unhandled exception while dispatching an incoming request. It generates a simple response describing the captured error using the format the client is expecting.
Provided arguments are
- the request context and
- an instance of
Error
describing the unhandled exception.
The method is invoked by renderFallback() in case some error has been captured to be handled. It isn't expected to return something, but to render a response using the provided request context.
javascript
api.service.Response.error( requestContext, someCapturedException );
Custom error response
There are two ways for implementing custom error responses.
This service can be replaced to overload this method. This is affecting default error responses as a whole.
A specially crafted type of
Error
can be thrown.A captured error may expose a method
respondToRequest()
which is invoked byerror()
with the request descriptor and response manager as arguments. If it is returning some truthy result, the default error response is omitted.javascript// config/routes.js export const routes = { "GET /api/foo/:id": ( req, res ) => { if ( req.params.id >= 1000 ) { throw new TooBigError( "ID must be less than 1000" ); } } } class TooBigError extends Error { respondToRequest( req, res ) { res.status( 400 ).json( { issue: "Provided ID is invalid.", details: this.message, } ); return true; } }
renderFallback()
This method is considered the fallback request handler which is invoked if no handler defined on a controller route has been found for the incoming request.
It is invoked with the request context and some optionally captured error as arguments.
splash()
This method is rendering a response indicating that the service has not finished its bootstrap process, yet. It is used on responding to incoming requests received early.