【发布时间】:2019-08-08 12:01:52
【问题描述】:
我有一个类LogException
public class LogException extends Exception {
public String ModuleName {get; set;}
public String StackTrace {get; set;}
public String ClassName {get; set;}
public String MethodName {get; set;}
public String ExceptionCause {get; set;}
public void log(Exception ex)
{
try
{
extractExceptionData(ex);
writeToObject(ex);
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
public LogException Module(String Name)
{
ModuleName = name;
return this;
}
public LogException ExceptionCause(String cause)
{
ExceptionCause = cause;
return this;
}
public void extractExceptionData(Exception ex)
{
try
{
stackTrace = ex.getStackTraceString().substringBefore('\n');
className = stackTrace.substringAfter('.').substringBefore('.');
methodName = stackTrace.substringBefore(':').substringAfter(className).substringAfter('.');
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
public void writeToObject(Exception ex)
{
try
{
// insert to object(database) here
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
}
我在这里实现了方法链接。因此,我可以调用像
这样的方法new LogException().Module('unitTestModule').Log(ex);
new LogException().ExceptionCause('divided by zero').Log(ex);
new LogException().Module('unitTestModule').ExceptionCause('Probably no data in account').Log(ex);
new LogException().ExceptionCause('Probably no data in account').Module('unitTestModule').Log(ex);
我的问题是,我怎样才能实现这个类,我只能在Module 之后调用ExceptionCause?
【问题讨论】:
-
为什么不直接使用重载的构造函数呢?方法链似乎没有添加任何东西,而且比精心挑选的一组构造函数要冗长得多。
-
@DavidReed :你能启发我/给我一个想法,我该如何实现重载的构造函数来实现它?
标签: design-patterns salesforce apex method-chaining