在Grails中使用HTTP状态代码呈现JSON的简单方法

在Grails中使用HTTP状态代码呈现JSON的简单方法,grails,groovy,Grails,Groovy,没有明确的“text/json”指定,有没有一种速记方法可以做到这一点 def remoteError = { render( status: 500, contentType: "text/json"){ error( exception: "a remote exception occurred") } } 我尝试将用作JSON…没有返回任何内容,但状态代码是正确的 render( status: 500, exception: params.exceptio

没有明确的
“text/json”
指定,有没有一种速记方法可以做到这一点

def remoteError = {     
  render( status: 500, contentType: "text/json"){
      error( exception: "a remote exception occurred")
  }
}
我尝试将
用作JSON
…没有返回任何内容,但状态代码是正确的

render( status: 500, exception: params.exception) as JSON 

如果使用converter参数,则不能像使用gsp视图时通常那样指定任何其他参数,如status。但是,可以在调用render之前设置响应状态:

response.status = 500
render([error: 'an error occurred'] as JSON)

这实际上会引发强制转换异常,因为
params.exception
是一个字符串。我尝试了
def errorMsg=[error:“发生了一个错误”]
将errorMsg呈现为JSON
,效果很好。@RaffiM当然,我改变了答案,呈现了一个贴图,而不是一个无法工作的字符串。我不得不做另一个轻微的调整,
将([error:'sdf']呈现为JSON)
,提示如下
render(status:500,text:(errors as JSON).toString(),contentType: 'application/json')