I have a service which returns an Option[ProductDoc] in a Future (as an akka ask)
How do I respond in spray routing so that a valid product repsonds with a product but an unknown but well formed one returns a 404?
I want the code to fill in the gap here :
get {
path("products" / PathElement) { productID:String =>
val productFuture = (productService ? ProductService.Get(productID)).mapTo[Option[ProductDoc]]
// THE CODE THAT GOES HERE SO THAT
// IF PRODUCT.ISDEFINED RETURN PRODUCT ELSE REJECT
}
}
The only way I can get to work is with this abomination :
get {
path(PathElement) { productID:String =>
val productFuture = (productService ? ProductService.Get(productID)).mapTo[Option[ProductDoc]]
provide(productFuture).unwrapFuture.hflatMap {
case x => provide(x)
} { hResponse:shapeless.::[Option[ProductDoc], HNil] =>
hResponse.head match {
case Some(product) => complete(product)
case None => reject
}
}
}
}
This can't be the correct way to achieve this, surely? This seems like a pretty simple pattern that must have been solved by someone already!
A 404 error is an HTTP status code that means that the page you were trying to reach on a website couldn't be found on their server . To be clear, the 404 error indicates that while the server itself is reachable, the specific page showing the error is not.
Another possibility is if a website has moved a page or resource but did so without redirecting the old URL to the new one. When that happens, you'll receive a 404 error instead of being automatically routed to the new page.
You can check to see which error IE is referring to by checking for either 404 or 400 in the title bar. 404 errors received when opening links via Microsoft Office applications generate a The Internet site reports that the item you requested could not be found (HTTP/1.0 404) message inside the MS Office program.
He writes troubleshooting content and is the General Manager of Lifewire. A 404 error is an HTTP status code that means that the page you were trying to reach on a website couldn't be found on their server . To be clear, the error indicates that while the server itself is reachable, the specific page showing the error is not.
Spray already has support for your use case: An option value None
is marshalled to an EmptyEntity
by default. This is probably what you were seeing before you made any changes: a 200 with an empty document. There's a directive which converts an empty document into a 404, rejectEmptyResponse
, which you wrap around parts of your route where you want this behavior.
Your route would then look just like this:
rejectEmptyResponse {
path("products" / PathElement) { productID:String =>
val productFuture = // same as before
complete(productFuture)
}
}
Of course, you can put the rejectEmptyResponse
inside the path depending on whether you want to wrap more route parts with it.
More info:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With