Grails 控制器中的异常处理 [英] Exception handling in Grails controllers

查看:15
本文介绍了Grails 控制器中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 Grails 中使用 UrlMappings 和 ErrorController 进行通用异常处理以进行通用异常处理,以便如果异常转义控制器,用户将被发送到通用错误页面并记录异常.我也知道如何使用 try/catch 块来处理特定的异常并尝试从中恢复.

I know how to do generic exception handling in Grails using UrlMappings and an ErrorController for generic exception handling, so that if an exception escapes a controller the user will be sent to a generic error page and the exception will be logged. I also know how to use try/catch blocks to handle specific exceptions and attempt to recover from them.

但在大多数控制器中,如果发生异常,我只想给用户一个稍微更具体的错误消息.所以在创建操作中,我想告诉用户该项目没有被创建.或者在导入操作中,我想告诉用户导入失败.现在,控制器看起来像:

But in most controllers, I just want to give the user a slightly more specific error message if an exception occurs. So in the create action, I want to tell the user that the item wasn't created. Or in the import action, I want to tell the user that the import failed. Right now, the controllers look like:

class ThingController {
  def create = {
    try {
      // The real controller code, which quickly hands it off to a service
    } catch (Exception e) {
      handleException(e, "There was an error while attempting to create the Thing")
    }
  }

  def delete = {
    try {
      // The real controller code, which quickly hands it off to a service
    } catch (Exception e) {
      handleException(e, "There was an error while attempting to delete the Thing")
    }
  }

  private void handleException(Exception e, String message) {
    flash.message = message
    String eMessage = ExceptionUtils.getRootCauseMessage(e)
    log.error message(code: "sic.log.error.ExceptionOccurred", args: ["${eMessage}", "${e}"])
    redirect(action:index)
  }
}

请注意,catch 块不会根据异常的类型或内容执行任何不同的操作;他们只是根据控制器给出稍微更具描述性的错误消息.真正的"控制器代码通常为 6-10 行,因此仅用于更改错误消息的额外 4 行代码似乎过多.此外,CodeNarc "CatchException" 规则抱怨,这强化了我的观点,即必须有更好的方法来做到这一点.我假设其他 Grails 应用程序也有类似的要求.什么是惯用方式来根据异常冒出的操作指定不同的错误消息?

Note that the catch blocks don't do anything different based on the type or content of the exception; they're just giving a slightly more descriptive error message based on the controller. The "real" controller code is usually 6-10 lines, so having an additional 4 lines of code just to change the error message seems excessive. In addition, the CodeNarc "CatchException" rule complains, which reinforces my opinion that there has to be a better way to do this. I assume other Grails applications have similar requirements. What is the idiomatic way to specify different error messages based on which action the exception bubbled out of?

我对来自解决此问题的特定方法的经验的答案感兴趣,或者更好的是,链接到代码库,在那里我可以在实践中看到解决方案.

I'm interested in answers that come from experience with a particular way of solving this problem, or even better, link to codebases where I can see the solution in practice.

推荐答案

Grails 具有一般处理控制器异常的机制.您可以在专用的错误控制器中执行此操作.常规控制器不需要使用 try/catch.

Grails has the mechanism for general handling controller exceptions. You can do this inside a dedicated Error controller. Regular controllers don’t need to use try/catch.

控制器:

class ThingController {
    def create() {
        def id = params.id as Long

        if (id == null) {
            throw new MissingPropertyException("thingId")
        }
        // The real controller code, which mostly parses things out and hands it
        // off to a service.
        // Service methods can throws exception

    }
}

在 UrlMappings 中添加处理 500 错误:

Add handling 500 error in UrlMappings:

class UrlMappings {

    static mappings = {
        // Exception handling in ErrorController
        "500"(controller: "error")
    }
}

错误控制器:

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

您可以使用这种方法处理 REST 和非 REST 异常.还有声明性异常处理插件,但我没有

You can handle REST and non-REST exceptions using this approach. Also there is Declarative Exception Handling plugin but I don’t have an

更新

您可以在错误控制器中获取特定的错误消息.当在控制器中抛出新的 RuntimeException(尝试删除事物时出现错误")时,在错误控制器中 request.exception.cause.message 将显示消息:尝试删除事物时出现错误".

You can get the specific error messages in Error controller. When in controller throw new RuntimeException ("There was an error while attempting to delete the Thing"), then in error controller request.exception.cause.message will show message: "There was an error while attempting to delete the Thing".

这篇关于Grails 控制器中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆