How to create a custom 404 page handler with Play 2.0?

后端 未结 7 2151
故里飘歌
故里飘歌 2021-01-03 19:22

What’s the preferred way to handle 404 errors with Play 2.0 and show a nice templated view?

7条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 19:41

    Please note that Play development team are making lots of efforts to move away from global state in Play, and hence GlobalSettings and the application Global object have been deprecated since version 2.4.

    HttpErrorHandler.onClientError should be used instead of GlobalSettings.onHandlerNotFound. Basically create a class that inherits from HttpErrorHandler, and provide an implementation for onClientError method.

    In order to find out type of error (404 in your case) you need to read status code, which is passed as a one of the method arguments e.g.

    if(statusCode == play.mvc.Http.Status.NOT_FOUND) {
        // your code to handle 'page not found' situation 
        // e.g. return custom implementation of 404 page
    }
    

    In order to let Play know what handler to use, you can place your error handler in the root package or configure it in application.conf using play.http.errorHandler configuration key e.g.

    play.http.errorHandler = "my.library.MyErrorHandler"
    

    You can find more details on handling errors here: for Scala or Java.

提交回复
热议问题