【问题标题】:Read request body after JSONException在 JSONException 之后读取请求正文
【发布时间】:2013-01-21 21:43:48
【问题描述】:

我有一个 Grails 控制器,它接受带有 JSON 正文的 POST 请求。在某些请求中,JSON 格式不正确,我收到 JSONException。如何获取请求正文以记录或检查它(我并不总是可以访问客户端)? Grails request.JSON 已经使用了流,所以看起来我无法通过 request.body 访问它。

这是我的控制器操作:

def setScore(ScoreCommand scoreCommand) {
   try {
      def context = request.JSON.optJSONObject("context")
      userService.updateContext(context)
   } catch (ConverterException ce) {
      log.error("Error parsing JSON")
      // I want to log the malformed JSON body
   }
   def scoreResponse
   if (!scoreCmd.validate()) {
      scoreResponse = errorResponse(scoreCommand)
   } else {
      def scoreResult = gameService.setScore(scoreCommand)
      scoreResponse = buildResponse(scoreResult)
   }
   render scoreResponse as JSON
}

【问题讨论】:

  • 它不起作用 :( 不幸的是,“context”在 POST 请求的正文中,而不是在参数中。
  • log.error("Error parsing JSON", ce) ?
  • 哦,它适用于 Isammoc。就如此容易。如果您将其作为答案,我可以将其设置为已接受。完整消息包含 JSONException 和格式错误的 JSON。

标签: json grails


【解决方案1】:

这行得通吗?

def json = request.JSON

try {
  def context = json.optJSONObject("context")
  userService.updateContext(context)
}catch(e) {
  log.error json.toString()
}

【讨论】:

  • 试过了,没有。一旦我访问“request.JSON”,它就会尝试解析它并抛出异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 2013-12-31
  • 2015-10-02
  • 1970-01-01
相关资源
最近更新 更多