简体   繁体   English

如何捕获NVelocity中的InvalidReference错误

[英]How to catch InvalidReference error in NVelocity

I am using codeplex NVelocity library on .net and i want to catch an error when I execute Evalute method on VelocityEngine instance and one of the parameter in template text was not found. 我在.net上使用codeplex NVelocity库,我想在VelocityEngine实例上执行Evalute方法时发现错误,并且找不到模板文本中的一个参数。

How can I obtain this? 我怎么能得到这个?

I find IInvalidReferenceEventHandler interface in NVelocity.App.Event namespace but I dont't find any information how to use it. 我在NVelocity.App.Event命名空间中找到了IInvalidReferenceEventHandler接口,但我找不到任何有关如何使用它的信息。 Any help will be appreciated. 任何帮助将不胜感激。

I've found the solution. 我找到了解决方案。

I've made EventHandler class: 我做了EventHandler类:

public class NVelocityEventHandler : IInvalidReferenceEventHandler, IMethodExceptionEventHandler
{
        #region IInvalidReferenceEventHandler Members

        public object InvalidGetMethod(NVelocity.Context.IContext context, string reference, object object_Renamed, string property, NVelocity.Util.Introspection.Info info)
        {
            return "InvalidGetMethod:" + reference;
        }

        public object InvalidMethod(NVelocity.Context.IContext context, string reference, object object_Renamed, string method, NVelocity.Util.Introspection.Info info)
        {
            return "InvalidMethod:" + reference;
        }

        public bool InvalidSetMethod(NVelocity.Context.IContext context, string leftreference, string rightreference, NVelocity.Util.Introspection.Info info)
        {
            return true;
        }

        #endregion

        #region IMethodExceptionEventHandler Members

        object IMethodExceptionEventHandler.MethodException(Type claz, string method, Exception e)
        {
            return "MethodException:" + method;
        }

        #endregion 
}

Then I use it in the code below: 然后我在下面的代码中使用它:

StringWriter writer = new StringWriter();
NVelocity.App.VelocityEngine eng = new NVelocity.App.VelocityEngine();
try
{
    NVelocityEventHandler te = new NVelocityEventHandler();
    EventCartridge ec = new EventCartridge();
    ec.AddEventHandler(te);
    VelocityContext vc = new VelocityContext((IDictionary)parameters);
    ec.AttachToContext(vc);
    eng.Evaluate(vc, writer, "templatestring", template);
}
catch (ParseErrorException pe)
{
    return pe.Message;
}
catch (MethodInvocationException mi)
{
    return mi.Message;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM