nemoo
(Nemoo)
1
I am very happy about the the new play 2.7 json error handler described here:
https://github.com/playframework/playframework/blob/master/documentation/manual/working/scalaGuide/main/http/ScalaErrorHandling.md
My play 2.6 scala application serves a gui that renders html pages and an api that serves Json.
I am wondering, will it be possible to use both a (custom) HtmlErrorHandler and a JsonHttpErrorHandler in the same app, for different controllers?
In application.conf I can only set a single play.http.errorHandler=“utils.ErrorHandler”
greg
(Greg Methvin)
2
This HtmlOrJsonHttpErrorHandler
should pretty much do what you want: https://www.playframework.com/documentation/2.7.x/ScalaErrorHandling#Using-both-HTML-and-JSON,-and-other-content-types
As long as you send your JSON requests with Accept: application/json
, this will send back a JSON response as requested by the client.
If you want to force it to use JSON for specific paths no matter what, you can implement something similar to https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/http/HttpErrorHandler.scala#L77, but instead of using the Accept header you’d use the path of the request to determine which error handler to use.
nemoo
(Nemoo)
3
Thanks a lot, exactly what I was looking for. I will probably be using it like this to use my custom http error handler:
@Singleton
class MyJsonOrHttpErrorHandler @Inject() (
jsonHandler: JsonHttpErrorHandler,
htmlHandler: MyHttpErrorHandler
) extends PreferredMediaTypeHttpErrorHandler(
"application/json" -> jsonHandler,
"text/html" -> htmlHandler
)
nemoo
(Nemoo)
4
I ended up doing just that. Works perfectly!