Error types(错误类型)¶
:::callout{theme="warning"} The following documentation is specific to TypeScript v1 functions. For more robust capabilities, including support for Ontology SDK and configurable resource requests, we recommend migrating to TypeScript v2. :::
In addition to declaring an output type on your TypeScript function, you can also declare an error type. This can be particularly useful for propagating and handling errors in the context of queries.
Define an error type¶
You can define an error type using the FunctionsError type exported from @foundry/functions-api. It takes two type parameters; a string name and an optional type that defaults to an empty object. Any valid output type for a function may be used as an error type, including objects and object sets.
You can union multiple FunctionsError types together to define a set of possible errors for your function. For example, you could define the following error type for a function that gets an employee's teammates:
import { FunctionsError } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
Declare an error type on a function¶
To declare an error type on a TypeScript function, you can use the FunctionsResult type exported from @foundry/functions-api. It takes two type parameters; an output type and an error type.
Using the GetTeammatesError example from the previous section, you can declare the error type on a function like so:
import { Function, FunctionsError, FunctionsResult } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
@Function()
public getTeammates(employeeId: string): FunctionsResult<Employee[], GetTeammatesError> {
...
}
Note that by default the FunctionsResult type includes a few errors that can be returned by the TypeScript function runtime infrastructure:
FunctionsTypeScriptExecutorService:CpuTimeoutError: Returned when the function exceeds the CPU time limit.FunctionsTypeScriptExecutorService:WallTimeoutError: Returned when the function exceeds the wall time limit.FunctionsTypeScriptExecutorService:OutOfMemoryError: Returned when the function exceeds the memory limit.FunctionsTypeScriptExecutorService:RuntimeError: Returned when the function encounters some other runtime error.
Return outputs and errors in your function¶
To return outputs and errors, you can use the FunctionsResult.ok and FunctionsResult.err methods exported from @foundry/functions-api:
FunctionsResult.ok: Takes a single output value as its argument.FunctionsResult.err: Takes an error name and value as its arguments.
Using the getTeammates example from the previous section, you can return outputs and errors like so:
import { Function, FunctionsError, FunctionsResult } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
@Function()
public getTeammates(employeeId: string): FunctionsResult<Employee[], GetTeammatesError> {
const employees = await Objects.search().employee([employeeId]).allAsync();
if (employees.length === 0) {
return FunctionsResult.err("EmployeeNotFoundForId", employeeId);
}
if (employees.length > 1) {
return FunctionsResult.err("MultipleEmployeesFoundForId", { employees, employeeId });
}
const employee = employees[0];
const teammates = await employee.teammates.allAsync();
return FunctionsResult.ok(teammates);
}
Handle errors from queries¶
When a function with an error type is called as a query from another repository, it returns a Result type response, which can be an ok or err result.
You can use the isOk or isErr type guards exported from @foundry/functions-api to differentiate between the two possible results. For instance, call the getTeammates example from the previous section, assuming you also published it as a query, and handle the response like so:
import { Function, isOk } from "@foundry/function-api";
import { getTeammates } from "@foundry/ontology-api/queries";
@Function()
public async myFunction(employeeId: string): Promise<string> {
const result = await getTeammates({ employeeId });
if (isOk(result)) {
const teammates = result.value;
// Do something with "teammates" here
...
}
// You can inspect the "name" field to case on each error by name and use the "value" field to get the error value
switch (result.error.name) {
case "EmployeeNotFoundForId": ...
case "MultipleEmployeesFoundForId": ...
case "FunctionsTypescriptExecutorService:OutOfMemoryError": ...
...
}
}
中文翻译¶
错误类型¶
:::callout{theme="warning"} 以下文档仅适用于 TypeScript v1 函数。如需更强大的功能,包括对 Ontology SDK 和可配置资源请求的支持,我们建议迁移至 TypeScript v2。 :::
除了在 TypeScript 函数中声明输出类型外,您还可以声明错误类型。这在查询(query)场景下传播和处理错误时尤为有用。
定义错误类型¶
您可以使用 @foundry/functions-api 导出的 FunctionsError 类型来定义错误类型。该类型接受两个类型参数:一个字符串名称和一个可选类型(默认为空对象)。任何函数的有效输出类型(包括对象和对象集)均可作为错误类型使用。
您可以将多个 FunctionsError 类型联合(union)在一起,为函数定义一组可能的错误。例如,您可以为获取员工队友的函数定义以下错误类型:
import { FunctionsError } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
在函数上声明错误类型¶
要在 TypeScript 函数上声明错误类型,您可以使用 @foundry/functions-api 导出的 FunctionsResult 类型。该类型接受两个类型参数:一个输出类型和一个错误类型。
使用上一节的 GetTeammatesError 示例,您可以像这样在函数上声明错误类型:
import { Function, FunctionsError, FunctionsResult } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
@Function()
public getTeammates(employeeId: string): FunctionsResult<Employee[], GetTeammatesError> {
...
}
请注意,默认情况下 FunctionsResult 类型包含一些可由 TypeScript 函数运行时基础设施返回的错误:
FunctionsTypeScriptExecutorService:CpuTimeoutError:当函数超过 CPU 时间限制时返回。FunctionsTypeScriptExecutorService:WallTimeoutError:当函数超过挂钟时间(wall time)限制时返回。FunctionsTypeScriptExecutorService:OutOfMemoryError:当函数超过内存限制时返回。FunctionsTypeScriptExecutorService:RuntimeError:当函数遇到其他运行时错误时返回。
在函数中返回输出和错误¶
要返回输出和错误,您可以使用 @foundry/functions-api 导出的 FunctionsResult.ok 和 FunctionsResult.err 方法:
FunctionsResult.ok:接受一个输出值作为参数。FunctionsResult.err:接受错误名称和错误值作为参数。
使用上一节的 getTeammates 示例,您可以像这样返回输出和错误:
import { Function, FunctionsError, FunctionsResult } from "@foundry/functions-api";
import { Employee } from "@foundry/ontology-api";
type GetTeammatesError =
| FunctionsError<"EmployeeNotFoundForId", string>
| FunctionsError<"MultipleEmployeesFoundForId", { employees: Employee[], employeeId: string }>
@Function()
public getTeammates(employeeId: string): FunctionsResult<Employee[], GetTeammatesError> {
const employees = await Objects.search().employee([employeeId]).allAsync();
if (employees.length === 0) {
return FunctionsResult.err("EmployeeNotFoundForId", employeeId);
}
if (employees.length > 1) {
return FunctionsResult.err("MultipleEmployeesFoundForId", { employees, employeeId });
}
const employee = employees[0];
const teammates = await employee.teammates.allAsync();
return FunctionsResult.ok(teammates);
}
处理查询中的错误¶
当带有错误类型的函数作为查询从其他仓库调用时,它会返回一个 Result 类型响应,该响应可以是 ok 或 err 结果。
您可以使用 @foundry/functions-api 导出的 isOk 或 isErr 类型守卫(type guard)来区分这两种可能的结果。例如,调用上一节的 getTeammates 示例(假设您已将其发布为查询),并像这样处理响应:
import { Function, isOk } from "@foundry/function-api";
import { getTeammates } from "@foundry/ontology-api/queries";
@Function()
public async myFunction(employeeId: string): Promise<string> {
const result = await getTeammates({ employeeId });
if (isOk(result)) {
const teammates = result.value;
// 在此处对 "teammates" 进行处理
...
}
// 您可以检查 "name" 字段以按名称对每个错误进行 case 处理,并使用 "value" 字段获取错误值
switch (result.error.name) {
case "EmployeeNotFoundForId": ...
case "MultipleEmployeesFoundForId": ...
case "FunctionsTypescriptExecutorService:OutOfMemoryError": ...
...
}
}