2013-01-21 57 views
1

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

这里是我的控制器操作:

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

'params.context'? –

+0

它不起作用:(不幸的是,“上下文”是在POST请求的主体中,而不是在参数中。 – chozero

+1

'log.error(“错误解析JSON”,ce)'? – Isammoc

回答

0

工作的呢?

def json = request.JSON 

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

尝试了它并且没有。只要我访问'request.JSON',它就尝试解析它并抛出异常 – chozero

+0

啊,我想知道是否是错误被抛出的时候。 – Gregg