KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

言語

エラー

前提条件が成り立つときだけ続行するには 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: &quot;Age cannot be negative: { $age }&quot;
      }" />
  </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 に束縛し、代替値を評価します。1種類のエラーだけを処理するには catch Validation => $err.message を、束縛名を指定するには catch Validation as problem => $problem.message を使います。代替値が null の場合は、元のエラーが伝播します。

@a() + @b() catch => 0 では、ハンドラーは呼び出しと加算の両方をカバーします。@a() + (@b() catch => 0) では、@b() だけをカバーします。

条件が成り立つときだけエラーを発生させるには throw if を使います。そのブロックの中では、1行につき1つのフィールドを書きます。KScript は条件を1回だけ評価します。フィールドは条件が真のときだけ評価されるため、成功した応答では e を完全に省略できます。

<fn name="result" params="reply: map">
  <if $reply->has('e')>
    <throw value="{
        type: 'Network'
        message: &quot;Host refused: {$reply.e.message}&quot;
        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 err) を持つ catch はすべてのエラーを処理します。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 を返すと宣言した関数は、その match を throw 分岐で終えられます。

<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 &quot;No press for { $button } yet&quot;
    }" />
</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 は左側の値がないときだけ実行されるので、必ず何かを見つける必要がある検索はそれを 1 行で書けます:

<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 &quot;There is no price for { $item }&quot;" />
</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' })はマップを開き、それ以外は空の { } も含めて文のブロックを開きます。エディターは両方を同じように扱います。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テストでは、メソッドハンドラーがエラーをその型のハンドラーに渡す例や、ログに記録された後のエラーを呼び出し元が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: &quot;{ $arg1 } and { $arg2 }&quot;)" />
</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: ...)を使うと、追加のデータを持つ汎用エラーを発生させられます。括弧の前の名前がエラーの型を決めます。汎用エラー、Validationなどの組み込み型、または自分で宣言した型にはErrorを使います。名前付き引数はフィールドになります。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']。どの呼び出し側からも見えて型チェックできるフィールドにするには、エラー型を宣言し、その型を catch します。

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.eur

backoffは呼び出しの間に待機します。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 をスローした項目は、値を次の項目に渡します。それ以外のエラーは本当の失敗なので、呼び出し元まで伝わります。項目内でのゼロ除算が「これではない」と誤解されることはありません。

どの項目も値を受け付けない場合に備えて、match と同じように最後の行を _ => value にできます。これがない場合、どれも受け付けなければ、値と試したすべての項目を示す Shape エラーが 1 つ発生します: 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する。catch NotFoundはPersonNotFoundもcatchします。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はすべてをcatchします。
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 インポート、設定、入力、再帰などの上限、誤った場所、OS、停止したスクリプト、廃止された機能、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)。