0

在使用此处报告的方案处理 Grails 2.2.4 中的异常时:

Grails 控制器中的异常处理

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

引发异常:

groovy.lang.MissingPropertyException: No such property: ExceptionMapper for class: ErrorController

用于一般处理控制器异常的 grails 机制是如何工作的?

建议的代码是 Grails 中的最佳实践/推荐方式吗?

4

2 回答 2

4

您从另一个问题复制了一些代码,但它使用了一个ExceptionMapper不属于 Groovy 或 Grails 的类(如果是,您需要一个 import 语句),并且没有在答案中定义。我不确定它的作用,但这样的事情应该有效:

def exception = request.exception.cause
response.status = 500
render(view: "/error", model: [exception: exception])
于 2013-10-23T17:23:13.300 回答
1

有许多帖子指向通过转发到视图来抛出和处理错误的旧方法。对于 Grails 2.3.0,最佳实践是遵循声明性异常处理方法:

Grails 控制器支持声明性异常处理的简单机制。如果控制器声明了一个接受单个参数的方法并且参数类型是 java.lang.Exception 或 java.lang.Exception 的某个子类,那么只要该控制器中的操作抛出该类型的异常,就会调用该方法。

class ElloController  {
def index() { 
    def message="Resource was not found"
    throw new NotFoundException(message);
}

def handleNotFoundExceptio(NotFoundException e) {
    response.status=404
    render ("error found")
}

异常处理的方法可以在 trait 中移动并为您想要的任何控制器实现。如果从服务中抛出错误,则可以在它正在调用该服务的控制器中对其进行跟踪。一篇描述处理 Grails 异常处理的文章

于 2015-01-20T08:53:26.580 回答