Skip to content

Custom Error Responses

Mathias edited this page Jul 26, 2011 · 5 revisions

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 Found error.
  • If the path matched but no route for the requests HTTP method is defined spray will produce a 405 Method Not Allowed error.
  • If the unmarshaller in your routes cannot deserialize the request content the response will be a 415 Unsupported Media Type error.
  • If the marshallers responsible for serialization of your custom object cannot produce a content type that the client accepts spray will return a 406 NotAcceptable error.

As discussed in the section about Rejections error 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.

Customizing Error Responses

By using a custom HttpService logic, derived from the default one, and overriding the respective rejection handlers it is easy to customize the created error responses, should the need arise. Also, if your routes create custom rejections you should use a custom HttpService for implementing the error response creation for these.

The HttpService is a simple class extending the HttpServiceActor and mixing in the HttpServiceLogic trait:

class HttpService(val route: Route) extends HttpServiceActor with HttpServiceLogic

In order to increase testability the HttpServiceActor has most of its code split out into HttpServiceLogic trait, which can be tested independently and without the requirement to fire up an actual actor. For using a custom HttpService implementation you should generate a sub trait of HttpServiceLogic (e.g. CustomServiceLogic) and create your CustomHttpService with

class CustomHttpService(val route: Route) extends HttpServiceActor with CustomServiceLogic

In this way you can test your CustomServiceLogic with SprayTest (see the Testing chapter) without the need to fire up actual actors.

Clone this wiki locally