Pregunta

I'm trying to use the respond method that exists in grails 2.3 to return some exception message and a status code in JSON format, but haven't got success with the return code this far..

I've set an ExceptionController that will handle all the exceptions thrown by the rest of the controllers. Here it is:

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
    }
}

But in a simple integration test, the result code is always 200..

I don't really know which is the correct format to use with this method to set the status code. I've tried several variations without success

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]

UPDATE I've found a format that works, but don't think it's the best solution...

respond JSON.parse("{'error':'${e.getMessage().encodeAsHTML()}'}"),[status:403]
¿Fue útil?

Solución

Have a look at https://github.com/grails/grails-core/commit/4e2f8de61f4383b92d79f5e34c3d1d0d151afb60. It seems you can use the property errorsHttpStatus but what I have read in the code is that you would need to pass an Errors instance not an exception.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top