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

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

问题描述

我知道如何使用UrlMappings和一个ErrorController通用异常处理在Grails中进行通用异常处理,以便如果一个异常逸出控制器,用户将被发送到一个通用的错误页面,异常将被记录。我也知道如何使用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.

推荐答案

p> 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

    }
}


$ b b

在UrlMappings中添加处理500错误:

Add handling 500 error in UrlMappings:

class UrlMappings {

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

ErrorController:

ErrorController:

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(尝试删除Thing时出现错误),然后在错误控制器request.exception.cause.message将显示消息:尝试删除时出现错误Thing。

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天全站免登陆