简体   繁体   中英

How to define a default Action for any http method in Play 2.1 (Scala)?

I'm writing RESTful web services using the Play framework (Scala variant), version 2.1.1.

For a given resource, I want to be able to process POST requests, but for any other method I want to return a MethodNotAllowed response.

My routes-file attempt (snippet):

# Item-related actions
POST    /item   controllers.ItemController.newItem
GET     /item   controllers.ApplicationController.methodNotAllowed
PUT     /item   controllers.ApplicationController.methodNotAllowed
DELETE  /item   controllers.ApplicationController.methodNotAllowed
HEAD    /item   controllers.ApplicationController.methodNotAllowed
OPTIONS /item   controllers.ApplicationController.methodNotAllowed
PATCH   /item   controllers.ApplicationController.methodNotAllowed

But I get a warning in the Play console:

[warn] /home/bruno/Entwicklung/pServer/conf/routes:8: unreachable code
[warn] PUT    /itemcontrollers.ApplicationController.methodNotAllowed

How come several, distinct routes can render some “unreachable code”? I understand the reverse-resolution mechanism should be given a clear set of rules in order to operate without ambiguities, but the direct mechanism, which is what I'm interested in right now, should be working out-of-the-box. Or not?

Since this case, from my point of view, must be rather common when programming REST services, I'm sure I'm missing something important here.

Should you have any suggestion as to the best way to approach this problem, I'll appreciate it.

You should not try to figure out all possible bad access points to generate error messages. Instead, you can override the onHandlerNotFound method in the application's Global object.

Adapted from Play's official documentation: ScalaGlobal

import play.api._
import play.api.mvc._
import play.api.mvc.Results.__

object Global extends GlobalSettings {
  override def onHandlerNotFound(request: RequestHeader): Result = {
    // implement methodNotAllowed controller Action
  }  
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM