GroovyCastException 元类 i18n

GroovyCastException metaclass i18n

这个问题与another有关。 我想向构造函数添加属性并覆盖 getLocalisedMessage() 函数以获得正确的错误翻译消息。首先我想重载构造函数来设置属性,但是当我添加:

GroovyCastException.metaClass.constructor = { Object objectToCast, Class classToCastTo ->
    def constructor = GroovyCastException.class.getConstructor(Object, Class)
    def instance = constructor.newInstance(objectToCast, classToCastTo)
    // ... do some further stuff with the instance ...
    println "Created ${instance} and executed!"
    instance
}

然后抛出 GroovyCastException 我没有在控制台中得到 println。

为什么?

如何重载构造函数,设置属性(objectToCast,classToCastTo)然后重载getLocalizedMessage?


我也试过:

def originalMapConstructor = GroovyCastException.metaClass.retrieveConstructor(Map)

GroovyCastException.metaClass.constructor = { Map m ->
    // do work before creation
    print "boot do work before creation "
    m.each{
        print it
    }
    print "boot do work before creation 2"
    def instance = originalMapConstructor.newInstance(m)
    // do work after creation
    print "boot do work after creation"
    instance
}

我把它放在控制器中(就在捕获异常之前)和 Bootstrap.groovy 中。不幸的是,控制台输出中没有 printlns。

你最好不要使用元编程来进行国际化。在 grails 中,如果可能,您应该在带有 <g:message> 标记的视图层中执行此操作。如果没有,下一个最佳选择是控制器层。

如果您只想在发生异常时在错误页面上显示本地化消息,最佳做法是使用“500”URL 映射,并使用 <g:renderException> 呈现异常在视图中。

如果要拦截异常,可以将“500”URL 映射更改为控制器并将其包装在那里,然后再传递给视图。示例:

// UrlMappings.groovy
class UrlMappings {
     static mappings = {
         ...
         "500"(controller:"error", method: "serverError")
     }
}

// ErrorController.groovy
class ErrorController {
    def serverError() {
        def exception = request.exception.cause
        if (exception instanceof GroovyCastException) {
            exception = new LocalizedGroovyCastException(exception)
        }
        [exception: exception]
    }
}

然后在新 class LocalizedGroovyCastException 中进行本地化。