【问题标题】:Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practiceGrails 2.2.4 最佳实践中使用 ExceptionMapper 处理 Grails 控制器中的异常
【发布时间】:2013-10-23 16:40:20
【问题描述】:

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

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

引发异常:

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

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

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

【问题讨论】:

  • 对于否决票,请说明需要对问题进行哪些更改,或者为什么它不适合 Stack Overflow。谢谢
  • 该评论是对未来读者的警告,我要求他们在投反对票之前向我展示如何改进(如果可能的话)。希望我的问题有用。
  • 你应该更乐观:)

标签: exception grails exception-handling controller


【解决方案1】:

您从另一个问题复制了一些代码,但它使用了不属于 Groovy 或 Grails 的 ExceptionMapper 类(如果是,您需要导入语句),并且未在答案中定义.我不确定它的作用,但是这样的东西应该可以工作:

def exception = request.exception.cause
response.status = 500
render(view: "/error", model: [exception: exception])

【讨论】:

  • 谢谢,我认为ExceptionMapper 是 Grails 的一部分,无需导入它。我会简短地尝试你的建议。
【解决方案2】:

有许多帖子指向通过转发到视图来抛出和处理错误的旧方法。 对于 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 中移动异常处理的方法,并为您想要的任何控制器实现。如果从服务中抛出错误,则可以在它正在调用该服务的控制器中对其进行跟踪。一篇描述Handling Grails Exception Handling的文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多