【问题标题】:Using respond method in Grails 2.3.6 with json format and status code在 Grails 2.3.6 中使用带有 json 格式和状态码的响应方法
【发布时间】:2014-03-07 09:57:54
【问题描述】:

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

我设置了一个 ExceptionController 来处理其余控制器抛出的所有异常。这里是:

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]

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的信息,但这不是我要问的
    • @Eylen 你在问什么?如果您查看grails.org/doc/2.3.x/guide/…,您会看到官方文档没有说明如何使用带有响应方法的状态码,您将不得不使用渲染方法。希望对您有所帮助!
    • 没错。 render 帮助设置状态码。 @Eylen 如果无论如何都使用JSON.parse,则使用respond 进行内容协商是没有意义的。 :)
    • 我想我没有明白这一点... Respond 不能用于返回除了状态 200 之外的任何内容?例如,如果我想返回一个数组,但说它是 403 禁止的,该怎么办?
    • 目前看来你不能。如果您认为这很有用,请提出一张功能票。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2012-05-30
    • 2017-09-07
    • 2019-12-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多