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