How to globally handle HTTP errors in Grails (stat

2019-04-08 04:38发布

问题:

Is there a way in Grails to catch all the possible HTTP errors before they're being sent to the client browser, as to be able to handle the content being sent to the client? I mean all 4xx and 5xx HTTP status codes, not only the 403, 404 and 500 like other have suggested.

What I'd like to do is to catch all HTTP errors in the first place, without having to specify them all one by one, then in a second step I would filter (e.g. in an error controller) specific error codes that I would like to handle (e.g. 400), but at least the ones that I would not specify would render to a generic error template I defined.

If this can't be done (or shouldn't be done), which HTTP errors codes should really be checked for and handled? I can at least see those codes happening at some point: 400, 401, 403, 404, 405, 500, 501, 503. And also, how should they be handled, using HTTP response codes mappings?

Thanks!

回答1:

haven't actually tried it but maybe a number constraint might work?

"$errorCode" {
     controller = "errors"
     action = "displayError"
     constraints {
          errorCode(matches:/\d{3}/)
     }
}