json - 在Grails 2.3.6中使用带有json格式和状态代码的response方法

标签 json grails http-status-codes grails-2.3

我正在尝试使用grails 2.3中存在的response方法来返回一些异常消息和JSON格式的状态码,但是到目前为止,返回码还没有成功。

我已经设置了一个ExceptionController,它将处理其余 Controller 抛出的所有异常。这里是:

class ExceptionController {

    static responseFormats = ['json','xml']

    def handleForbiddenException(ForbiddenException e){
        respond 'error':e.getMessage(),status:403
    }

    def handleNotFoundException(NotFoundException e){
        respond 'error':e.getMessage(),status:404
    }

    def handleInvalidRequestException(InvalidRequestException e){
        respond 'error':e.getMessage(), status:422
    }

    def handleGeneralException(Exception e){
        respond 'error':e.getMessage(),status:500
    }
}

但是在简单的集成测试中,结果代码始终为200。

我真的不知道哪种方法与该方法一起使用来设置状态代码。我尝试了几种变体而没有成功
respond 'error':e.getMessage(), status:422
respond e.getMessage(), status:422
respond object:['error':e.getMessage()], arguments:[status:422]
respond object:['error':e.getMessage()], model:[status:422]
respond object:['error':e.getMessage()], [status:422]

更新我找到了一种有效的格式,但不认为这是最好的解决方案...
respond JSON.parse("{'error':'${e.getMessage().encodeAsHTML()}'}"),[status:403]

最佳答案

看看https://github.com/grails/grails-core/commit/4e2f8de61f4383b92d79f5e34c3d1d0d151afb60。看来您可以使用errorsHttpStatus属性,但是我在代码中读到的是您需要传递一个Errors实例而不是异常。

关于json - 在Grails 2.3.6中使用带有json格式和状态代码的response方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22246862/

相关文章:

c# - 向客户端发送状态码 500 时页面未呈现

php - 如何在不维护状态名称数组的情况下用PHP发送状态代码?

json - 从 URL 解析 JSON 数据并显示在 TableView 上

json - Newtonsoft.JSON 使用 GUID 序列化\反序列化数据表

grails - grails 用于处理上传文件的不同类

grails - Grails 2,战法-> java.lang.ClassNotFoundException:grails.test.mixin.services.ServiceUnitTestMixin

javascript - 在本地保存 JSON 文件

javascript - 在 Javascript 中解析 Laravel JSON 对象抛出错误

grails - 缩小.war

http - 如果删除仅部分成功,要使用正确的 http 状态代码吗?