Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.
class CustomerServiceActor extends Actor with CustomerService with AjaxService {
implicit def json4sFormats: Formats = DefaultFormats
def actorRefFactory = context
def receive = runRoute(handleExceptions(myExceptionHandler)(
customerRoutes ~ ajaxRoutes))
//capture all exceptions within the above routes
implicit def myExceptionHandler(implicit log: LoggingContext) =
ExceptionHandler.apply {
case e: SomeCustomException => ctx => {
log.debug("%s %n%s %n%s".format(e.getMessage, e.getStackTraceString, e.getCause))
ctx.complete(404, e.getMessage)
}
case e: Exception => ctx => {
log.debug("%s %n%s %n%s".format(e.getMessage, e.getStackTraceString, e.getCause))
ctx.complete(500, e.getMessage)
}
}
}
//separate trait file
trait CustomRejectionHandler extends HttpService {
implicit val myRejectionHandler = RejectionHandler {
case AuthenticationFailedRejection(credentials) :: _ => complete(Unauthorized, "Credential fail " + credentials)
case _ => complete(BadRequest, "Something went wrong here")
}
//HttpService
class CustomerServiceActor extends Actor with CustomerService with AjaxService with CustomRejectionHandler {
. . . .
def receive = runRoute(handleRejections(myRejectionHandler)(handleExceptions(myExceptionHandler)(
customerRoutes ~ ajaxRoutes)))
implicit def myExceptionHandler(implicit log: LoggingContext) =
ExceptionHandler.apply {
. . . .
}
}
More information on Handling Rejections at spray-routing/key-concepts/rejections/
//application.conf
spray.can.server {
request-timeout = 10s
}
//in HttpService class
class CustomerServiceActor extends Actor with CustomerService with AjaxService with CustomRejectionHandler {
. . . .
def receive = handleTimeouts orElse runRoute(handleRejections(myRejectionHandler)(handleExceptions(myExceptionHandler)(
customerRoutes ~ ajaxRoutes)))
def handleTimeouts: Receive = {
case Timedout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Something is taking way too long.")
}
. . . .
More information on Timeout Handler at spray-routing/key-concepts/timeout-handling/