错误
仅当前置条件成立时才继续执行,请使用guard condition else { ... }。失败块必须通过return、throw、break、continue或exit离开当前流程。
<fn name="save_age" params="age: int, enabled: bool">
<guard test="$enabled">
<return value="'Skipped'" />
</guard>
<if $age < 0>
<throw value="{
type: 'Validation'
message: "Age cannot be negative: { $age }"
}" />
</if>
<return value="'Saved'" />
</fn>
<echo value="@save_age(-1, true) catch => $err.message" />fn save_age(age: int, enabled: bool) {
guard $enabled else {
return 'Skipped'
}
throw if $age < 0 {
type: 'Validation'
message: "Age cannot be negative: { $age }"
}
return 'Saved'
}
echo @save_age(-1, true) catch => $err.message后缀catch在求值成功时保留其左侧的值。当求值抛出错误时,KScript会将该错误绑定到$err并计算备用值。若只想处理某一种错误类型,请使用catch Validation => $err.message;若要为绑定命名,请使用catch Validation as problem => $problem.message。备用值为null时,会将原始错误继续向上抛出。
在@a() + @b() catch => 0中,处理器同时覆盖调用和加法运算。在@a() + (@b() catch => 0)中,它只覆盖@b()。
当某个条件成立时才抛出错误,请使用throw if。在其代码块内,每行写一个字段。KScript只对条件求值一次,且仅当条件为真时才对字段求值,因此成功的响应可以完全省略e。
<fn name="result" params="reply: map">
<if $reply->has('e')>
<throw value="{
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}" />
</if>
<return value="$reply.r" />
</fn>
<try>
<echo value="@result({ r: 'ready' })" />
<catch type="Network" as="err">
<echo>Request failed ({$err['code']}): {$err.message}</echo>
</catch>
</try>fn result(reply: map) {
throw if $reply->has('e') {
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}
return $reply.r
}
try {
echo @result({ r: 'ready' })
} catch Network as err {
echo "Request failed ({$err['code']}): {$err.message}"
}<try>
<let name="data" value="@read_json($path)" />
<catch type="FileNotFound">
<echo>No file at {$path}, using defaults.</echo>
</catch>
<catch as="err">
<echo>Failed: {$err.message} (line {$err.line})</echo>
</catch>
<finally>
<echo>done</echo>
</finally>
</try>
<throw type="Validation">Age must be positive, got {$age}</throw>try {
$data = @read_json($path)
} catch FileNotFound {
echo "No file at {$path}, using defaults."
} catch err {
echo "Failed: {$err.message} (line {$err.line})"
} finally {
echo 'done'
}
throw Validation "Age must be positive, got {$age}"catch接受它所处理的错误类型,类型之间用|连接,as用于为错误命名:catch FileNotFound | Permission as e。只有小写名称的catch(catch err)会处理所有错误。when用于添加测试:catch Network as e when $e.status == 503。catch按顺序尝试,第一个匹配的会被执行。错误类型名称以大写字母开头,这是catch区分它们与变量名的方式。
未知元素、属性和语法错误会在脚本启动之前报告,因此末尾的一个拼写错误不会让任务只完成一半。
未被捕获的错误会以KScript错误的形式打印出来,包括错误发生的位置和类型,脚本以退出码3结束:
ERROR app.kscript:2:11: Name: Unknown command @nope().kscript对所有失败都以这种方式显示,包括脚本、kscript serve错误页面以及所有其他命令,绝不会以.NET异常的形式出现。由计算机而非脚本引起的失败会获得与之匹配的错误类型(FileNotFound、Access、IO、Network等),而kscript未预料到的失败则是Internal错误,这是值得报告的缺陷。若要查看错误背后的.NET异常和堆栈跟踪,请使用--stack-trace运行(放在脚本路径之前:kscript --stack-trace app.kscript),或设置KSCRIPT_STACK_TRACE=1,该设置同样适用于kscript serve和已编译的程序。
在值的位置 throw
throw 既是语句也是值,因此 match 分支、?? 的右侧或 ? : 的一侧可以用错误终止,而不是给出值。它的写法与语句相同:双引号中的类型和消息、单独的消息、由类型创建的错误或捕获的错误。它从不给出值,所以适用于任何期望某种类型的地方,检查器从其余部分读取类型:声明返回 int 的函数可以用 throw 分支结束它的 match。
<fn name="press" params="display: int, button: string" returns="int">
<return value="match $button {
'[oct]' => $display * 8
'[two]' => $display * 2
// Every other button stops here, with the button in the message.
_ => throw Validation "No press for { $button } yet"
}" />
</fn>
<!-- 32 because [oct] has an arm -->
<echo value="@press(4, '[oct]') catch => $err.message" />
<!-- 'No press for [mem] yet' because no arm fits [mem] -->
<echo value="@press(4, '[mem]') catch => $err.message" />fn press(display: int, button: string): int {
return match $button {
'[oct]' => $display * 8
'[two]' => $display * 2
// Every other button stops here, with the button in the message.
_ => throw Validation "No press for { $button } yet"
}
}
// 32 because [oct] has an arm
echo @press(4, '[oct]') catch => $err.message
// 'No press for [mem] yet' because no arm fits [mem]
echo @press(4, '[mem]') catch => $err.message在 ?? 之后,只有左侧的值缺失时 throw 才会运行,因此必须找到结果的查找可以用一行表达:
<let name="prices" value="{ tea: 3, coffee: 4 }" />
<fn name="price_of" params="item: string, prices: map" returns="int">
<return value="$prices[$item] ?? throw NotFound "There is no price for { $item }"" />
</fn>
<echo value="@price_of('tea', $prices) catch NotFound => 0" /> <!-- 3 because tea has a price, so the throw never ran -->
<echo value="@price_of('cake', $prices) catch NotFound => 0" /> <!-- 0 because cake has no price, so the throw ran -->$prices = { tea: 3, coffee: 4 }
fn price_of(item: string, prices: map): int {
return $prices[$item] ?? throw NotFound "There is no price for { $item }"
}
echo @price_of('tea', $prices) catch NotFound => 0 // 3 because tea has a price, so the throw never ran
echo @price_of('cake', $prices) catch NotFound => 0 // 0 because cake has no price, so the throw ran? : 也是如此,只有被选中的一侧会运行:$count > 0 ? $count : throw Validation "A basket holds at least one item"。catch 的回退值中单独的 throw 会原样再次给出捕获的错误:@load() catch => throw。
需要多个值的分支可以包含一个由语句组成的 { } 块,就像 match 语句的分支那样。它的 return 给出分支的值,块中可以看到 $it 以及 match 周围的变量:
<let name="limit" value="2" />
<let name="label">match 3 {
1 => 'one'
_ => {
if $it > $limit {
// 'more than 2' because 3 is over the limit
return "more than { $limit }"
}
return 'a few'
}
}</let>
<echo value="$label" /> <!-- 'more than 2' -->$limit = 2
$label = match 3 {
1 => 'one'
_ => {
if $it > $limit {
// 'more than 2' because 3 is over the limit
return "more than { $limit }"
}
return 'a few'
}
}
echo $label // 'more than 2'分支的 => 之后的 {,若先出现键和冒号(_ => { name: 'Ada' })则开启一个 map,否则开启一个语句块,包括空的 { }。编辑器以相同方式检查两者:在 throw 之后补全错误类型、在分支块中补全语句、为 throw 及其类型着色,并在这样抛出的错误可能逃出脚本时发出警告(KS5016)。
函数与类型上的处理器
将catch附加到函数或方法上,即可为每个调用者处理错误。将其附加到类型上,则可在该类型的所有方法之间共享同一处理器。
最近的匹配处理器会先运行。返回一个非null值即可恢复。false、0和''等值均可使用。单独的throw、null返回值,或处理器执行到末尾,都会把原始错误传递给下一个外层处理器。
<type name="Directory">
<field name="fallback" type="string" />
<fn name="lookup" params="key: string">
<if !$key->is_blank()>
<return value="$key" />
</if>
<if !$this.fallback->is_blank()>
<return value="$this.fallback" />
</if>
<throw type="Validation">A key is required</throw>
</fn>
<catch type="Validation" as="err">
<return value="$err.message" />
</catch>
</type>
<let name="directory" value="Directory(fallback: 'guest')" />
<echo value="$directory->lookup('owner')" /> <!-- owner -->
<echo value="$directory->lookup('')" /> <!-- guest -->
<let name="empty" value="Directory(fallback: '')" />
<echo value="$empty->lookup('')" /> <!-- A key is required -->type Directory {
fallback: string
fn lookup(key: string) {
if !$key->is_blank() => return $key
if !$this.fallback->is_blank() => return $this.fallback
throw Validation "A key is required"
}
} catch Validation as err {
return $err.message
}
$directory = Directory(fallback: 'guest')
echo $directory->lookup('owner') // owner
echo $directory->lookup('') // guest
$empty = Directory(fallback: '')
echo $empty->lookup('') // A key is required在处理程序内部,当条件成立时,throw if condition 会重新抛出当前错误。添加 payload 块可以抛出新的错误。仅记录错误的处理程序会让错误继续向上传播。可运行的 catch 测试展示了方法处理程序将错误传递给其类型的处理程序,以及调用方在错误被记录后捕获该错误。
使用 /// @throws Network 记录可能到达调用方的错误。悬停提示和签名帮助会显示已知错误。在脚本的顶层,当已知错误可能逃逸时,kscript check 和编辑器会发出警告(KS5016)。
对于单次调用,使用 catch 以内联方式获取结果。
<echo value="@testing(1, 2) catch Error => $err.message" />
<fn name="testing" params="arg1: number, arg2: number">
<throw value="Error(message: "{ $arg1 } and { $arg2 }")" />
</fn>echo @testing(1, 2) catch Error => $err.message
fn testing(arg1: number, arg2: number) {
throw Error(message: "{ $arg1 } and { $arg2 }")
}带值和原因抛出错误
使用 throw Error(message: ..., value: ..., cause: ...) 抛出带有额外数据的通用错误。括号前的名称决定错误类型。Error 用于通用错误,Validation 等内置类型,或你自己声明的类型。具名参数会成为字段。message: 设置说明,cause: 在你包装先前错误时保存该错误。
<let name="age" value="-1" />
<try>
<try>
<throw type="Validation">Age must be positive, got {$age}</throw>
<catch type="Validation" as="original">
<throw value="Error(
message: 'Could not save profile',
value: $age,
cause: $original
)" />
</catch>
</try>
<catch type="Error" as="err">
<echo>{ $err.type }: { $err.message }</echo>
<echo>Rejected value: { $err.value }</echo>
<echo>Caused by: { $err.cause.message }</echo>
</catch>
</try>$age = -1
try {
try {
throw Validation "Age must be positive, got {$age}"
} catch Validation as original {
throw Error(
message: 'Could not save profile',
value: $age,
cause: $original
)
}
} catch Error as err {
echo "{ $err.type }: { $err.message }"
echo "Rejected value: { $err.value }"
echo "Caused by: { $err.cause.message }"
}Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1抛出第一个错误时省略 cause:。添加到内置错误上的字段(如这里的 value:),在同一文件中捕获该类型或其父类型的任何 catch 里都可以用点语法($err.value)读取,编辑器也会补全它。如果错误是在另一个文件中抛出的,请用方括号读取:$err['value']。若希望每个调用方都能发现并检查这些字段,请声明一个错误类型并捕获该类型。
如果你已经有一个包含 type、message 及其他字段的映射,可以用 throw $payload 直接抛出该映射。将映射作为第一个参数传给 Error($payload) 会将其转换为消息文本。错误构造函数在编辑器补全中提供具名参数。
在 XML 中,同样的抛出写作 <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />。外层 XML 的 value 属性保存整个错误表达式。内层 value: 参数是该错误上的额外字段。若只需类型和消息,<throw type="Validation" message="Invalid age" /> 对应 throw Validation "Invalid age"。
重试
某些失败会自行消失:数据库繁忙、网络短暂中断,或 API 正在限流。@retry(times, work) 会调用 work,并在每次抛出错误时再次调用,总共最多 times 次。它返回 work 的结果,或抛出最后一个错误。work 会接收尝试次数,第一次为 1:
<fn name="fetch_rates" params="attempt: int">
<if $attempt < 3>
<throw type="Timeout">The rates service is busy</throw>
</if>
<return value="{ eur: 0.86 }" />
</fn>
<let name="rates" value="@retry(3, @fetch_rates, backoff: 100ms)" />
<echo value="$rates.eur" />fn fetch_rates(attempt: int) {
if $attempt < 3 => throw Timeout "The rates service is busy"
return { eur: 0.86 }
}
$rates = @retry(3, @fetch_rates, backoff: 100ms)
echo $rates.eurbackoff 在两次调用之间等待。when 会接收错误并决定是否重试,因此永远不会成功的错误会立即失败:@retry(5, @charge, when: fn(err) => $err.type == 'Timeout')。
依次尝试
有些值可能是几种情况之一,要弄清楚是哪一种,就得逐个尝试每种解读,直到有一种可行。try each $value |> first, second 按顺序用该值调用每一项,并返回第一个结果。每一项可以是类型(调用 NumberEntry($label) 会检查标签),也可以是函数:
<fn name="digits" params="text: string" description="The number in text that is only digits." returns="int">
<if not $text->matches(/^[0-9]+$/)>
<throw type="Validation">'{$text}' isn't digits</throw>
</if>
<return value="$text->to_int()" />
</fn>
<fn name="word" params="text: string" description="The number in a word: one, two or three." returns="int">
<let name="numbers" value="{ one: 1, two: 2, three: 3 }" />
<if not $numbers->has($text)>
<throw type="Validation">'{$text}' isn't a number word</throw>
</if>
<return value="$numbers[$text]" />
</fn>
<echo value="try each '12' |> @digits, @word" /> <!-- 12, because @digits reads it -->
<echo value="try each 'two' |> @digits, @word" /> <!-- 2, because @digits throws and @word reads it -->
<echo value="try each 'many' |> @digits, @word, _ => 0" /> <!-- 0, because neither reads it -->
<!-- A longer list goes one item per line, each after a comma. -->
<fn name="reading" params="text: string" returns="int" value="try each $text |>
@digits,
@word,
_ => 0" />
<echo value="@reading('three')" /> <!-- 3, because @word reads it -->/// The number in text that is only digits.
fn digits(text: string): int {
if not $text->matches(/^[0-9]+$/) => throw Validation "'{$text}' isn't digits"
return $text->to_int()
}
/// The number in a word: one, two or three.
fn word(text: string): int {
$numbers = { one: 1, two: 2, three: 3 }
if not $numbers->has($text) => throw Validation "'{$text}' isn't a number word"
return $numbers[$text]
}
echo try each '12' |> @digits, @word // 12, because @digits reads it
echo try each 'two' |> @digits, @word // 2, because @digits throws and @word reads it
echo try each 'many' |> @digits, @word, _ => 0 // 0, because neither reads it
// A longer list goes one item per line, each after a comma.
fn reading(text: string): int => try each $text |>
@digits,
@word,
_ => 0
echo @reading('three') // 3, because @word reads it抛出 Shape(值不符合类型)或 Validation 的项会把值传给下一项。其他任何错误都是真正的失败,因此会一直向上传给调用方:项内部的除以零错误绝不会被误当作"不是这一项"。
最后一行可以是 _ => value,就像在 match 中一样,用于没有任何项接受该值的情况。如果没有这一行,没有项接受该值时会产生一个 Shape 错误,其中列出该值和尝试过的每一项:the string 'many' fits none of @digits, @word.
在调用的括号内,各项之间的逗号会被当作调用本身的逗号,因此要把 try each 放在单独的括号中:expect((try each 'one' |> @digits, @word), same: 1)。
类型的工厂通常是对由它派生的类型使用的 try each。
错误类型
使用 error 声明你自己的错误类型。字段的用法与 type 中相同,消息可以使用它们,extends 说明错误的种类:
<error name="PersonNotFound" message="No person with id {$id}" description="No person has that id." extends="NotFound">
<field name="id" type="int" />
</error>
<error name="OutOfStock" status="409" message="{$item} is out of stock">
<field name="item" type="string" />
<field name="left" type="int" default="0" />
</error>
<fn name="find_person" params="id: int">
<throw value="PersonNotFound(id: $id)" />
</fn>
<try>
<do>@find_person(42)</do>
<catch type="NotFound" as="e">
<echo>{ $e.message } ({ $e.type }, status { $e.status })</echo>
</catch>
</try>/// No person has that id.
error PersonNotFound(message: "No person with id {$id}") extends NotFound {
id: int
}
error OutOfStock(status: 409, message: "{$item} is out of stock") {
item: string
left: int = 0
}
fn find_person(id: int) {
throw PersonNotFound(id: $id)
}
try {
@find_person(42)
} catch NotFound as e {
echo "{ $e.message } ({ $e.type }, status { $e.status })"
}- 抛出。
throw PersonNotFound(id: 42)创建错误并将其抛出。它的参数包括按名称指定的字段,以及message:(代替类型的默认消息)和cause:(导致此错误的先前错误)。没有默认值的字段必须提供,编辑器会标记缺失和未知的字段。throw Validation "Too short"对于没有字段的类型仍然有效,throw Validation(field: 'name', message: 'Too short')则为内置类型添加字段。 - 捕获。
catch NotFound也会捕获PersonNotFound,因为它继承自NotFound。在 catch 中,$e.id读取一个字段,编辑器会补全 catch 所指定类型的字段。每个错误都有type、message、line、column、file、status和cause。$e->is(NotFound)在代码中检查类型,$e->chain()列出它:['PersonNotFound', 'NotFound', 'Error']。 - 重新抛出与包装。在 catch 中,单独的
throw会原样重新抛出正在处理的错误。throw $e对已保存的错误做同样的事。要添加上下文,请包装它:throw ConfigBroken(path: $path, cause: $e),然后$err.cause.message读取原始错误。 - 不抛出地创建。
OutOfStock(item: 'tea')将错误作为值返回,以便稍后返回或抛出。 - 状态。
status是当没有任何东西捕获错误时,KScript.Http 路由返回的 HTTP 状态码。类型会从其所继承的类型中继承该状态码,以及字段和消息。 - 导出。顶层错误类型会像函数和类型一样被导出,因此
import "errors/payment-failed.kscript"可以引入它们。kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"将其写入errors/。
KScript 自身抛出的内置错误类型形成一棵树,catch 遵循这棵树:
| 类型 | 继承自 | 引发于 |
|---|---|---|
Error |
每个错误。catch Error 捕获所有错误。 |
|
Syntax, Name, Null, Argument, Value, Const, Math |
Error |
脚本中的错误:语法错误、未知名称、需要值时却为 null、参数错误、值错误、修改 const、除以零。Index 继承自 Value,用于列表之外的位置。 |
Type |
Error |
错误类型的值。Shape 继承它,用于不符合 type 的数据($e.problems 列出每个问题)。 |
Format |
Error |
格式错误的文本。Json 和 Yaml 继承它。 |
IO |
Error |
文件。FileNotFound、Permission 和 Access 继承它。 |
Network |
Error |
请求。Timeout 继承它,$e.status 是响应的状态码。 |
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal |
Error |
导入、设置、输入、递归等限制、错误的位置、操作系统、已停止的脚本、已废弃的功能、KScript.Http 应用、语言模型、桌面窗口、文档引用、失败的测试检查,以及 KScript 自身的故障。 |
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) |
Error |
供你自己的代码抛出或继承。数字即 HTTP 状态码。 |
Query, Connection (503) |
Error |
KScript.Data:数据库拒绝的查询、无法打开的数据库。Migration:无法读取或运行的迁移,或无法继续执行的 kscript db 命令。ModelNotFound 继承 NotFound;UniqueViolation 和 ForeignKeyViolation 继承 Conflict;MultipleRecordsFound(来自 ->sole())继承 Query。 |
JobFailed |
Error |
KScript.Queue:用完重试次数的任务。JobTimeout 继承 Timeout。 |
没有类型名以 Error 结尾:它们都是错误。(QueryError 和 ConnectionError 现在分别是 Query 和 Connection,catch QueryError 对此有说明。)
catch 或 throw 中的名称既未声明也非内置时仍然可用(作为 Error 的一种),但编辑器会对其发出警告(KS5011),因为它通常是拼写错误。