KScript docs
EN

The language

Errors

Use guard condition else { ... } to continue only when a precondition holds. The failure block must leave the current flow with return, throw, break, continue, or 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

A postfix catch preserves the value on its left when evaluation succeeds. When it throws, KScript binds the error to $err and evaluates the fallback. Use catch Validation => $err.message to recover from one error type, or catch Validation as problem => $problem.message to name the binding. A null fallback propagates the original error.

In @a() + @b() catch => 0, the handler covers both calls and the addition. In @a() + (@b() catch => 0), it covers only @b().

Use throw if to raise an error only when a condition holds. Inside its block, write one field per line. KScript evaluates the condition once. It evaluates the fields only when the condition is true, so a successful reply can omit e entirely.

<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 takes the error types it handles, joined by |, and as names the error: catch FileNotFound | Permission as e. A catch with only a lower-case name (catch err) handles every error. when adds a test: catch Network as e when $e.status == 503. Catches are tried in order and the first that fits runs. Error type names start with a capital letter, which is how catch tells them from the variable's name.

Unknown elements, attributes and syntax errors are reported before a script starts, so a typo near the end doesn't leave a job half done.

An error nothing catches is printed as a KScript error, with where it happened and its type, and the script exits with code 3:

Text
   ERROR  app.kscript:2:11: Name: Unknown command @nope().

kscript shows every failure this way, in scripts, kscript serve error pages and all the other commands, never as a .NET exception. A failure that comes from the computer rather than the script gets the error type that fits (FileNotFound, Access, IO, Network and so on), and one kscript didn't expect is an Internal error, which is a bug worth reporting. To see the .NET exception and stack trace behind an error, run with --stack-trace (before the script's path: kscript --stack-trace app.kscript) or set KSCRIPT_STACK_TRACE=1, which also works for kscript serve and compiled programs.

Handlers on functions and types

Attach a catch to a function or method to handle errors for every caller. Attach it to a type to share a handler across its methods.

The nearest matching handler runs first. Return a non-null value to recover. Values such as false, 0, and '' all work. A bare throw, a null return, or reaching the end of the handler passes the original error to the next enclosing handler.

<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

Inside a handler, throw if condition rethrows the current error when the condition holds. Add a payload block to raise a new error. A handler that only logs the error lets it propagate. The runnable catch tests show a method handler passing an error to its type's handler and a caller catching an error after it was logged.

Use /// @throws Network to document an error that can reach the caller. Hover and signature help show known errors. At the top level of a script, kscript check and the editor warn when a known error can escape (KS5016).

For a single call, recover the result inline with 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 with a value and a cause

Use throw Error(message: ..., value: ..., cause: ...) to raise a generic error with extra data. The name before the parentheses sets the error type. Use Error for a generic error, a built-in type such as Validation, or a type you declare yourself. The named arguments become fields. message: sets the explanation and cause: holds the earlier error when you wrap one.

<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 }"
}
Text
Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1

Omit cause: when raising the first error. Use bracket lookup, such as $err['value'], for fields added directly to a built-in error. For fields callers should be able to discover and type-check, declare an error type and catch that type. Its declared fields can be read with dot syntax, such as $err.value.

If you already have a map with type, message, and other fields, throw the map directly with throw $payload. Passing the map as the first argument to Error($payload) converts it to message text. The error constructor offers named arguments in editor completion.

In XML, the same throw is <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />. The outer XML value attribute holds the entire error expression. The inner value: argument is the extra field on that error. For a type and message alone, <throw type="Validation" message="Invalid age" /> corresponds to throw Validation "Invalid age".

Trying again

Some failures go away on their own: a busy database, a network blip, an API that is rate limiting you. @retry(times, work) calls work, and calls it again each time it throws, up to times calls in all. It returns what work returns, or throws the last error. work is given the attempt, 1 for the first:

<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 waits between calls. when is given the error and says whether to try again, so a mistake that will never succeed fails at once: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout').

Error types

Declare your own error types with error. Fields work as in a type, the message can use them, and extends says what kind of error it is:

<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 })"
}
  • Throwing. throw PersonNotFound(id: 42) makes the error and throws it. Its arguments are its fields, by name, plus message: (instead of the type's message) and cause: (the error that led to this one). A field without a default must be given, and the editor flags missing and unknown fields. throw Validation "Too short" still works for a type with no fields, and throw Validation(field: 'name', message: 'Too short') adds fields to a built-in one.
  • Catching. catch NotFound catches PersonNotFound too, because it extends NotFound. In the catch, $e.id reads a field, and the editor completes the fields of the types the catch names. Every error has type, message, line, column, file, status and cause. $e->is(NotFound) checks the type in code, and $e->chain() lists it: ['PersonNotFound', 'NotFound', 'Error'].
  • Rethrowing and wrapping. A bare throw inside a catch rethrows the error it is handling, unchanged. throw $e does the same with a saved error. To add context, wrap it: throw ConfigBroken(path: $path, cause: $e), then $err.cause.message reads the original.
  • Making one without throwing. OutOfStock(item: 'tea') gives the error as a value, to return or throw later.
  • Status. status is the HTTP status a KScript.Http route answers with when nothing catches the error. A type inherits it, and its fields and message, from the type it extends.
  • Exports. Top-level error types are exported, like functions and types, so import "errors/payment-failed.kscript" brings them in. kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int" writes one to errors/.

The built-in error types, which KScript itself raises, form a tree that catch follows:

Type Extends Raised for
Error Every error. catch Error catches everything.
Syntax, Name, Null, Argument, Value, Const, Math Error Mistakes in a script: bad syntax, an unknown name, null where a value is needed, wrong arguments, a bad value, changing a const, dividing by zero. Index extends Value, for a position outside a list.
Type Error A value of the wrong type. Shape extends it, for data that doesn't fit a type ($e.problems lists each problem).
Format Error Text in the wrong format. Json and Yaml extend it.
IO Error Files. FileNotFound, Permission and Access extend it.
Network Error Requests. Timeout extends it, and $e.status is the response's status.
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal Error Imports, settings, input, limits such as recursion, the wrong place, the OS, a stopped script, retired features, KScript.Http apps, language models, desktop windows, a document's references, failed test checks, a fault in KScript itself.
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) Error For your own code to throw or extend. The number is the HTTP status.
Query, Connection (503) Error KScript.Data: a query the database refused, a database that can't be opened. Migration: a migration that can't be read or run, or a kscript db command that can't go ahead. ModelNotFound extends NotFound; UniqueViolation and ForeignKeyViolation extend Conflict; MultipleRecordsFound (from ->sole()) extends Query.
JobFailed Error KScript.Queue: a job that used up its tries. JobTimeout extends Timeout.

No type's name ends in Error: they are all errors. (QueryError and ConnectionError are now Query and Connection, and catch QueryError says so.)

A name in catch or throw that is neither declared nor built in still works (as a kind of Error), but the editor warns about it (KS5011), since it is usually a typo.

Edit this page on GitHub