Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practice

若如初见. 提交于 2019-12-11 23:12:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!