从Grails命令对象验证中返回特定的HTTP错误代码

时间:2016-09-20 12:55:25

标签: rest validation grails

如果设置一个REST端点(例如保存用户),是否可以使用命令对象validate()来获取特定的HTTP错误代码,这些代码只能返回给Controller处理回应?

我想避免Controller操作必须处理大量if块,检查特定错误消息,并将其查找/转换为HTTP错误代码的情况。

例如,如果无法在数据库中找到匹配的用户,我希望自定义验证器以某种方式告诉控制器返回404。

以下不是我尝试过的。相反,它只是我想用于验证REST参数的理想结构的概念证明。也许这是完全错误的,或者有更好的方法。如果有,那也是受欢迎的。

e.g:

User.groovy

...
class User {
    String username

    static constraints = {
        username unique:true
    }
}

UserController.groovy

...
class UserController extends RestfulController {
    def update(UserCommand userCmd) {
        /*
         * Not actually working code, but proof of concept of what 
         * I'm trying to achieve
         */
        render status: userCmd.validate()
    }

    class UserCommand {
        Long id
        String username

        static constraints = {
            importFrom User

            /* 
             * I also get that you can't return Error codes via the 
             * custom validator, but also just to illustrate what I'm
             * trying to achieve
             */
            id validator: { 
                User user = User.get(id)
                if(user == null) {
                    return 404
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

所以你的例子没有多大意义。如果您正在保存用户但无法找到,那很好,不是吗?如果您要更新用户,则可能在控制器中调用struct操作。

那说,虽然这似乎是一个好主意,但由于它不起作用,我建议更像以下内容:

update()

您可以调整它以处理您的命令对象,但我认为这可以提供更多class UserController { def edit() { withUser { user -> [user:user] } } private def withUser(id="id", Closure c) { def user = User.get(params[id]) if(user) { c.call user } else { flash.message = "The user was not found." response.sendError 404 } } } 的一般概念。

答案 1 :(得分:0)

也许您应该尝试返回404但是然后是您解析的实际错误并使用

执行其他操作

您不会在第一个实例(that will make proper sense and actually valid)

中使用大量错误代码
if (userCmd.validate()) {
  def error=userCmd.errors.allErrors.collect{g.message(error : it)}
  render status:404,text: error
  return
}
//otherwise 
 render status:201, text: 'something'

你也可以

response.status=404
render "Some content"