代码之家  ›  专栏  ›  技术社区  ›  Peter Starbek

如何在NVelocity中捕获InvalidReference错误

  •  5
  • Peter Starbek  · 技术社区  · 16 年前

    我正在使用codeplex 模板引擎

    我怎样才能得到这个?

    IInvalidReferenceEventHandler 接口位于NVelocity.App.Event命名空间中,但我找不到如何使用它的任何信息。任何帮助都将不胜感激。

    1 回复  |  直到 16 年前
        1
  •  3
  •   Peter Starbek    16 年前

    我找到了解决办法。

    我创建了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 
    }
    

    然后我在下面的代码中使用它:

    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;
    }
    
    推荐文章