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