Bruno Unna
Bruno Unna

Reputation: 1454

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.

Upvotes: 1

Views: 501

Answers (1)

mor
mor

Reputation: 2313

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
  }  
}

Upvotes: 2

Related Questions