datai/docs/archive/api-docs/apex/2026-01-27-013-2-api.md

95 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# API 文档Apex 动态代码执行服务
## 元数据
- 需求编号REQ-013-2
- 创建时间2026-01-27
- 创建人AI Assistant
- 状态:已发布
## API 概述
本模块提供对 Salesforce Apex 代码的动态执行能力。它作为一个无状态的 API 代理,封装了 Salesforce SOAP API 的 `executeAnonymous` 方法。主要功能包括执行匿名 Apex 代码块、配置调试日志级别、解析执行结果以及处理编译和运行时异常。
该服务主要通过 `ApexExecutorService` 接口暴露给上层应用(如 Controller
## 接口列表
### 1. 执行 Apex 代码
- **方法签名**`ExecuteResult execute(String apexCode, DebuggingOptions options)`
- **功能描述**:在连接的 Salesforce 组织中执行一段匿名的 Apex 代码,并根据选项返回执行结果和日志。
- **所属接口**`com.datai.apex.core.ApexExecutorService`
#### 请求参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| apexCode | String | 是 | 需要执行的 Apex 代码片段。例如:`System.debug('Hello');` |
| options | DebuggingOptions | 否 | 调试选项,用于控制日志级别。如果为 null将使用默认配置System/Apex_Code 为 DEBUG其他为 INFO。 |
#### 响应参数 (`ExecuteResult`)
| 字段名 | 类型 | 说明 |
|---|---|---|
| success | boolean | 执行是否成功(无未捕获的运行时异常)。 |
| compiled | boolean | 代码是否编译通过。 |
| debugLog | String | 完整的调试日志内容。 |
| exceptionMessage | String | 异常信息(编译错误描述或运行时异常消息)。 |
| exceptionStackTrace | String | 异常堆栈跟踪(仅运行时异常)。 |
| executionTime | Long | 执行耗时(毫秒)。 |
#### 异常说明
- **ApexCompilationException**:当 Apex 代码存在语法错误导致编译失败时抛出。包含详细的行列号和错误信息。
- **ApexConnectionException**:当无法连接到 Salesforce 或 API 调用失败(网络问题、认证失效)时抛出。
### 2. 模型详解
#### DebuggingOptions
用于配置 Salesforce 的 `DebuggingHeader`
- **属性**
- `categories` (Map<LogCategory, LogCategoryLevel>): 日志类别与级别的映射。
- `preset` (String): 预设配置名称(预留字段)。
- **LogCategory 枚举**`Db`, `Workflow`, `Validation`, `Callout`, `Apex_code`, `Apex_profiling`, `Visualforce`, `System`, `All`.
- **LogCategoryLevel 枚举**`None`, `Error`, `Warn`, `Info`, `Debug`, `Fine`, `Finer`, `Finest`.
#### ExecuteResult
执行结果的统一封装。
- **设计初衷**:统一处理成功和失败场景,前端可以直接通过 `success``compiled` 字段判断状态,而无需解析复杂的 SOAP Fault。
## 示例
### 调用示例 (Java)
```java
@Autowired
private ApexExecutorService apexExecutorService;
public void runApex() {
String code = "System.debug('Hello World');";
// 配置日志级别
DebuggingOptions options = new DebuggingOptions();
options.addCategory(LogCategory.Apex_code, LogCategoryLevel.Debug);
try {
ExecuteResult result = apexExecutorService.execute(code, options);
if (result.isSuccess()) {
System.out.println("Log: " + result.getDebugLog());
} else {
System.err.println("Runtime Error: " + result.getExceptionMessage());
}
} catch (ApexCompilationException e) {
System.err.println("Compile Error: " + e.getMessage());
}
}
```
## 相关文档
- [需求文档](../requirements/REQ-013-2.md)
- [设计文档](../design/2026-01-27-013-2-Apex动态代码执行与日志管理设计.md)