When a controller returns a InternalServerError, I want a custom page to render the error messages in a user friendly way.
I found this documentation on the internet
https://www.playframework.com/documentation/2.3.x/ScalaGlobal
Now I understand that the above URL is no longer valid for Playframework 2.7. I searched more and found this
https://www.playframework.com/documentation/2.7.x/ScalaErrorHandling
But this is not the same as the older error handler. In the past I could have handled onHandlerNotFound
and onBadRequest
and onInternalServerError
but now I all I can handle is onServerError
With the new approach of extending from HttpErrorHandler
How can I send my response to a custom error page depending on each type of error.
Edit: Maybe the question is not clear. In the error handler I want to send the errors to a custom error page. This was shown in the example of play 2.3.x where I could do
object Global extends GlobalSettings {
override def onError(request: RequestHeader, ex: Throwable) = {
Future.successful(InternalServerError(
views.html.errorPage(ex)
))
}
}
I want to do something similar in Play 2.7.x and beyond.
If you want to provide a custom error page for an unhandled exception, as you could in Play 2.3 using onError
method, in Play 2.7 implement ErrorHandler.onServerError
method.
For Bad Request and Not Found and other client errors, there is ErrorHandler.onClientError
method to implement, that allows returning custom templates based on the status code.
import javax.inject.Singleton
import play.api.http.DefaultHttpErrorHandler
import play.api.http.Status._
import play.api.mvc.Results._
import play.api.mvc._
import scala.concurrent._
@Singleton
class ErrorHandler extends DefaultHttpErrorHandler {
override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
statusCode match {
case NOT_FOUND => Future.successful(NotFound(views.html.notFound()))
case BAD_REQUEST => Future.successful(BadRequest(views.html.badRequest()))
case _ => super.onClientError(request, statusCode, message)
}
}
override def onServerError(request: RequestHeader, ex: Throwable): Future[Result] = {
Future.successful(
InternalServerError(views.html.errorPage(ex))
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.