0

我正在尝试使用 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]
4

1 回答 1

1

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

于 2014-03-07T12:15:31.637 回答