首页 > 解决方案 > 顶点中的条件方法链接

问题描述

我有一个类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);

我的问题是,我怎样才能实现这个类,以便我只能ExceptionCause在之后调用Module

标签: design-patternssalesforceapexmethod-chaining

解决方案


我不会在这里使用方法链接。我只是重写构造函数来填充所需的参数:

public LogException(String module, String exceptionCause) {
}

public LogException(String module) {
    this(module, null);
}
// etc.

你在这里唯一不能做的就是有两个构造函数,它们都接受一个String参数——你必须愿意通过额外的可选参数来定义所需的层次结构,就像exceptionCause这里一样。

参考文档是Apex Constructors


推荐阅读