问题
While handling exception in Grails 2.2.4 with the scheme reported here:
Exception handling in Grails controllers
class ErrorController {
def index() {
def exception = request.exception.cause
def message = ExceptionMapper.mapException(exception)
def status = message.status
response.status = status
render(view: "/error", model: [status: status, exception: exception])
}
}
an exception is raised:
groovy.lang.MissingPropertyException: No such property: ExceptionMapper for class: ErrorController
How does the grails mechanism for general handling of controller exceptions works?
The code proposed is a best practice/recommended way in Grails?
回答1:
You copied some code from another question, but it uses an ExceptionMapper
class that isn't part of Groovy or Grails (and if it were you'd need an import statement), and isn't defined in the answer. I'm not sure what it does, but something like this should work:
def exception = request.exception.cause
response.status = 500
render(view: "/error", model: [exception: exception])
回答2:
There are many posts pointing to the old way of throwing and handling errors by forwarding to a view. With Grails 2.3.0, the best practice would be to follow the declarative exception handling approach:
Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is java.lang.Exception or some subclass of java.lang.Exception, that method will be invoked any time an action in that controller throws an exception of that type.
class ElloController {
def index() {
def message="Resource was not found"
throw new NotFoundException(message);
}
def handleNotFoundExceptio(NotFoundException e) {
response.status=404
render ("error found")
}
The methods for exception handling can be moved in a trait and implemented for any controller you want. If an error is thrown from a service, it can be traced in the controller it is invoking the service. An article describing the Handling Grails Exception Handling
来源:https://stackoverflow.com/questions/19547486/exception-handling-in-grails-controllers-with-exceptionmapper-in-grails-2-2-4-be