【问题标题】:Grails: On 404 error need to know name of controller and action that caused itGrails:关于 404 错误需要知道控制器的名称和导致它的操作
【发布时间】:2014-04-10 06:52:58
【问题描述】:

在 URL 映射文件中,我已将 404 错误与 ErrorController 的 notFound 操作联系起来。

class UrlMappings {
static mappings = {
    "/$controller/$action?/$id?"{
        constraints {
            // apply constraints here
        }
    }
    "500"(controller: "errorPage", action: "internalError")
    "403"(controller: "errorPage", action: "forbidden")
    "404"(controller: "errorPage", action: "notFound") 
}

如果任何控制器不进行渲染调用并且该操作不存在默认视图,它会调用 ErrorPageController 的 notFound 操作。现在,我想知道在这个 notFound 操作中调用了哪个操作,因为调用了 404 异常。怎么可能知道?例如,在 500 的情况下,internalError 操作获取 request.exception,通过它我们知道调用 internalError 发生了什么。 404错误也需要做同样的事情。

【问题讨论】:

    标签: grails


    【解决方案1】:

    我试过这个控制器:

    package test
    class ErrorPageController {
        def grailsUrlMappingsHolder
        def grailsApplication
    
        def notFound() {
            // retrieve uri without context (if any)
            def uri = request.forwardURI - "/${grailsApplication.metadata['app.name']}"
    
            // try to parse uri agains defined urlMappings to get parameters
            def parameters = grailsUrlMappingsHolder.match(uri)?.parameters ?: [:]
            [previousAction : parameters.action, previousController: parameters.controller]
        }
    }
    

    我假设在你的路径中上下文是你的appName,你可能需要相应地调整它。

    【讨论】:

    • request.forwardURI ......这就是我错过的......谢谢它对我有用
    【解决方案2】:

    你可能会使用像提到的http://grails.org/doc/2.2.1/ref/Plug-ins/filters.html这样的grails通配符过滤器

    然后在此处打印您需要的内容,例如控制器名称和操作。在每个控制器/动作执行之前都会调用过滤器。

    【讨论】:

    • 我已经设置了过滤器。在重定向到 notFound 操作之前会调用过滤器,因此无法在过滤器处知道当前请求是否会导致 404 错误。另外,我不想打印我想将导致 notFound 的控制器和操作名称存储在 notFound 操作本身中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多