2009-10-16 134 views
5

我在.net上使用codeplex NVelocity庫,當我在VelocityEngine實例上執行Evalute方法時發現錯誤,並且未找到模板文本中的某個參數。如何捕捉NVelocity中的InvalidReference錯誤

我該如何獲得這個?

我覺得IInvalidReferenceEventHandler接口在NVelocity.App.Event命名空間,但我沒有找到任何信息如何使用它。任何幫助將不勝感激。

回答

3

我找到了解決方案。

我做了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; 
}