-
Notifications
You must be signed in to change notification settings - Fork 0
Custom Error Responses
All predefined route directives produce proper HTTP status codes and error messages according to the requirements of the HTTP spec if something goes wrong. For example:
- If the request cannot be handled because no path filter matched spray will produce a
404 Not Founderror. - If the path matched but no route for the requests HTTP method is defined spray will produce a
405 Method Not Allowederror. - If the unmarshaller in your routes cannot deserialize the request content the response will be a
415 Unsupported Media Typeerror. - If the marshallers responsible for serialization of your custom object cannot produce a content type that the client
accepts spray will return a
406 NotAcceptableerror.
As discussed in the section about Rejections errors in spray are handled by a two-level logic. First the error is wrapped in a Rejection, where it is stored and maybe overcome by another subsequent route in the route structure that is able to successfully handle the request. If the rejection cannot be overcome it is the job of the HttpService to generate an error response for the set of rejections created by the routing structure.
When you create an HttpService you can optionally pass a custom RejectionHandler to the constructor.
A RejectionHandler is defined like this:
type RejectionHandler = PartialFunction[List[Rejection], HttpResponse]
The cc.spray.RejectionHandler.Default partial function implements the default translations. A good approach is to
write translations for "interesting" rejections yourself and delegate to the default handler in all other cases:
val myRejectionHandler: RejectionHandler = {
case AuthenticationFailedRejection(realm) :: _ =>
HttpResponse(Unauthorized, "Naaah, boy!!")
}
val myService = Actor.actorOf {
new HttpService(
route = mainModule.route,
rejectionHandler = myRejectionHandler
orElse RejectionHandler.Default
)
}
- Home
- Requirements
- spray-server
- ... Getting Started
- ... Key Concepts
- ...... Request Lifecycle
- ...... Routes
- ...... Directives
- ...... Composing Directives
- ...... Rejections
- ...... Marshalling and Unmarshalling
- ... Predefined Directives
- ...... Method Filters
- ...... Path Filters
- ...... Parameter Filters
- ...... Form-Field Filters
- ...... Marshalling/Unmarshalling
- ...... Caching
- ...... Detach
- ...... Encoding/Decoding
- ...... Authentication/Authorization
- ...... File and Resource Directives
- ...... Misc Directives
- ... Advanced Topics
- ...... Case Class Extraction
- ...... Custom Directives
- ...... Custom Media Types
- ...... Custom Error Responses
- ... Configuration
- ... Testing
- ... Example Projects
- spray-client
- Patch Policy
- Credits
- Sponsors