Errori
Usa guard condition else { ... } per continuare solo quando una precondizione è vera. Il blocco di fallimento deve uscire dal flusso corrente con return, throw, break, continue oppure 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.messageUn catch postfisso conserva il valore alla sua sinistra quando la valutazione riesce. Quando lancia un errore, KScript lega l'errore a $err e valuta il fallback. Usa catch Validation => $err.message per recuperare da un solo tipo di errore, oppure catch Validation as problem => $problem.message per dare un nome al binding. Un fallback null propaga l'errore originale.
In @a() + @b() catch => 0, il gestore copre sia le chiamate sia la somma. In @a() + (@b() catch => 0), copre solo @b().
Usa throw if per sollevare un errore solo quando una condizione è vera. Dentro il suo blocco, scrivi un campo per riga. KScript valuta la condizione una sola volta. Valuta i campi solo quando la condizione è vera, quindi una risposta riuscita può omettere del tutto 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 riceve i tipi di errore che gestisce, separati da |, e as dà un nome all'errore: catch FileNotFound | Permission as e. Un catch con solo un nome in minuscolo (catch err) gestisce ogni errore. when aggiunge un test: catch Network as e when $e.status == 503. I catch vengono provati in ordine e viene eseguito il primo che corrisponde. I nomi dei tipi di errore iniziano con una maiuscola, che è il modo in cui catch li distingue dal nome della variabile.
Elementi sconosciuti, attributi e errori di sintassi vengono segnalati prima dell'avvio di uno script, quindi un refuso verso la fine non lascia un lavoro a metà.
Un errore che nessun catch intercetta viene stampato come errore KScript, con il punto in cui è avvenuto e il suo tipo, e lo script termina con codice 3:
ERROR app.kscript:2:11: Name: Unknown command @nope().kscript mostra ogni errore in questo modo, negli script, nelle pagine kscript serve di errore e in tutti gli altri comandi, mai come eccezione .NET. Un errore che dipende dal computer e non dallo script riceve il tipo di errore adatto (FileNotFound, Access, IO, Network e così via), mentre un errore che kscript non si aspettava è un errore Internal, cioè un bug da segnalare. Per vedere l'eccezione .NET e lo stack trace dietro un errore, esegui con --stack-trace (prima del percorso dello script: kscript --stack-trace app.kscript) oppure imposta KSCRIPT_STACK_TRACE=1, che funziona anche per kscript serve e i programmi compilati.
throw al posto di un valore
throw è un valore oltre che un'istruzione, quindi un ramo di match, la destra di ?? o un lato di ? : possono fermarsi con un errore invece di dare un valore. Si scrive come l'istruzione: un tipo e un messaggio tra virgolette doppie, un messaggio da solo, un errore creato da un tipo o un errore catturato. Non dà mai un valore, quindi va bene ovunque sia atteso un tipo qualsiasi, e il controllo legge il tipo dal resto: una funzione che dichiara di restituire un int può terminare il suo match con un ramo 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 "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.messageDopo ?? un throw viene eseguito solo quando manca il valore a sinistra, così una ricerca che deve trovare qualcosa lo dice in una riga:
<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 ranLo stesso vale per ? :, dove viene eseguito solo il lato scelto: $count > 0 ? $count : throw Validation "A basket holds at least one item". Un throw da solo nel valore di ripiego di un catch restituisce di nuovo l'errore catturato, invariato: @load() catch => throw.
Un ramo che ha bisogno di più di un valore può contenere un blocco { } di istruzioni, come un ramo di un'istruzione match. Il suo return dà il valore del ramo, e il blocco vede $it e le variabili attorno al 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'Un { dopo il => di un ramo apre una mappa quando vengono prima una chiave e i due punti (_ => { name: 'Ada' }), altrimenti un blocco di istruzioni, compreso un { } vuoto. L'editor controlla entrambi allo stesso modo: completa i tipi di errore dopo throw e le istruzioni nel blocco di un ramo, colora throw e il suo tipo, e avvisa quando un errore lanciato così può uscire dallo script (KS5016).
Gestori su funzioni e tipi
Collega un catch a una funzione o a un metodo per gestire gli errori di ogni chiamante. Collegalo a un tipo per condividere un gestore tra i suoi metodi.
Viene eseguito per primo il gestore corrispondente più vicino. Restituisci un valore non null per recuperare. Valori come false, 0 e '' funzionano tutti. Un throw nudo, un ritorno null, oppure raggiungere la fine del gestore passa l'errore originale al gestore successivo che lo racchiude.
<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 requiredDentro di un gestore, throw if condition rilancia l'errore corrente quando la condizione è vera. Aggiungi un blocco payload per sollevare un nuovo errore. Un gestore che si limita a registrare l'errore lo lascia propagare. I test di catch eseguibili mostrano un gestore di metodo che passa un errore al gestore del suo tipo, e un chiamante che intercetta un errore dopo che è stato registrato.
Usa /// @throws Network per documentare un errore che può arrivare al chiamante. Il suggerimento al passaggio del mouse e l'aiuto sulla firma mostrano gli errori noti. Al livello superiore di uno script, kscript check e l'editor avvisano quando un errore noto può sfuggire (KS5016).
Per una singola chiamata, recupera il risultato in linea con 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 }")
}Lancia con un valore e una causa
Usa throw Error(message: ..., value: ..., cause: ...) per sollevare un errore generico con dati extra. Il nome prima delle parentesi imposta il tipo di errore. Usa Error per un errore generico, un tipo predefinito come Validation, o un tipo che dichiari tu. Gli argomenti con nome diventano campi. message: imposta la spiegazione e cause: contiene l'errore precedente quando ne incapsuli uno.
<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 -1Ometti cause: quando lanci il primo errore. Un campo aggiunto a un errore integrato, come value: qui, si legge con la notazione a punto ($err.value) in qualsiasi catch di quel tipo, o di un tipo da cui eredita, nello stesso file, e l'editor lo completa. Quando l'errore viene lanciato in un altro file, leggilo con le parentesi quadre: $err['value']. Per campi che ogni chiamante possa scoprire e verificare, dichiara un tipo di errore e cattura quel tipo.
Se hai già una mappa con type, message e altri campi, lanciala direttamente con throw $payload. Passare la mappa come primo argomento di Error($payload) la converte in testo del messaggio. Il costruttore dell'errore offre argomenti con nome nel completamento dell'editor.
In XML, lo stesso lancio è <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />. L'attributo value esterno contiene l'intera espressione di errore. L'argomento value: interno è il campo extra su quell'errore. Per solo tipo e messaggio, <throw type="Validation" message="Invalid age" /> corrisponde a throw Validation "Invalid age".
Riprovare
Alcuni errori si risolvono da soli: un database occupato, un calo di rete, un'API che limita le richieste. @retry(times, work) chiama work e la richiama ogni volta che lancia un errore, fino a times chiamate in tutto. Restituisce ciò che restituisce work, oppure lancia l'ultimo errore. work riceve il tentativo, 1 per il primo:
<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 attende tra una chiamata e l'altra. when riceve l'errore e decide se riprovare, così un errore che non potrà mai riuscire fallisce subito: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout').
Provare ciascuno a turno
Alcuni valori possono essere una tra diverse cose, e per scoprirlo si prova ogni lettura finché una non funziona. try each $value |> first, second chiama ogni elemento con il valore, in ordine, e restituisce il primo risultato. Un elemento può essere un tipo (chiamare NumberEntry($label) controlla l'etichetta) o una funzione:
<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 itUn elemento che lancia Shape (un valore che non corrisponde a un tipo) o Validation passa il valore all'elemento successivo. Qualsiasi altro errore è un vero fallimento, quindi risale fino al chiamante: una divisione per zero dentro un elemento non viene mai scambiata per “non è questo”.
L'ultima riga può essere _ => value, come in un match, per quando nessun elemento accetta il valore. Senza di essa, se nessuno lo accetta si ha un unico errore Shape che indica il valore e ogni elemento provato: the string 'many' fits none of @digits, @word.
Dentro le parentesi di una chiamata, le virgole degli elementi verrebbero lette come quelle della chiamata, quindi metti il try each tra parentesi proprie: expect((try each 'one' |> @digits, @word), same: 1).
La factory di un tipo è di solito un try each sui tipi derivati da esso.
Tipi di errore
Dichiara i tuoi tipi di errore con error. I campi funzionano come in un type, il messaggio può usarli, e extends indica che tipo di errore è:
<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 })"
}- Lancio.
throw PersonNotFound(id: 42)crea l'errore e lo lancia. I suoi argomenti sono i suoi campi, per nome, piùmessage:(al posto del messaggio del tipo) ecause:(l'errore che ha portato a questo). Un campo senza valore predefinito deve essere fornito, e l'editor segnala i campi mancanti e sconosciuti.throw Validation "Too short"funziona ancora per un tipo senza campi, ethrow Validation(field: 'name', message: 'Too short')aggiunge campi a uno predefinito. - Intercettazione.
catch NotFoundintercetta anchePersonNotFound, perché estendeNotFound. Nel catch,$e.idlegge un campo, e l'editor completa i campi dei tipi nominati dal catch. Ogni errore hatype,message,line,column,file,statusecause.$e->is(NotFound)verifica il tipo nel codice, e$e->chain()lo elenca:['PersonNotFound', 'NotFound', 'Error']. - Rilancio e incapsulamento. Un semplice
throwdentro un catch rilancia l'errore che sta gestendo, invariato.throw $efa lo stesso con un errore salvato. Per aggiungere contesto, incapsulalo:throw ConfigBroken(path: $path, cause: $e), poi$err.cause.messagelegge l'originale. - Crearlo senza lanciarlo.
OutOfStock(item: 'tea')restituisce l'errore come valore, da restituire o lanciare più tardi. - Stato.
statusè lo stato HTTP con cui risponde un KScript.Http route quando nulla intercetta l'errore. Un tipo eredita questo valore, insieme ai suoi campi e al messaggio, dal tipo che estende. - Esportazioni. I tipi di errore di primo livello vengono esportati, come funzioni e tipi, quindi
import "errors/payment-failed.kscript"li importa.kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"ne scrive uno inerrors/.
I tipi di errore predefiniti, che KScript stesso solleva, formano un albero che catch segue:
| Tipo | Estende | Sollevato per |
|---|---|---|
Error |
Ogni errore. catch Error intercetta tutto. |
|
Syntax, Name, Null, Argument, Value, Const, Math |
Error |
Errori nello script: sintassi errata, nome sconosciuto, null dove serve un valore, argomenti sbagliati, valore non valido, modifica di una const, divisione per zero. Index estende Value, per una posizione fuori da una lista. |
Type |
Error |
Un valore del tipo sbagliato. Shape lo estende, per dati che non entrano in un type ($e.problems elenca ogni problema). |
Format |
Error |
Testo nel formato sbagliato. Json e Yaml lo estendono. |
IO |
Error |
File. FileNotFound, Permission e Access lo estendono. |
Network |
Error |
Richieste. Timeout lo estende, e $e.status è lo stato della risposta. |
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal |
Error |
Importazioni, impostazioni, input, limiti come la ricorsione, il posto sbagliato, il sistema operativo, uno script interrotto, funzioni ritirate, app KScript.Http, modelli linguistici, finestre desktop, i riferimenti di un documento, controlli di test non riusciti, un guasto in KScript stesso. |
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) |
Error |
Da lanciare o estendere nel tuo codice. Il numero è lo stato HTTP. |
Query, Connection (503) |
Error |
KScript.Data: una query rifiutata dal database, un database che non si può aprire. Migration: una migrazione che non si può leggere o eseguire, o un comando kscript db che non può procedere. ModelNotFound estende NotFound; UniqueViolation e ForeignKeyViolation estendono Conflict; MultipleRecordsFound (da ->sole()) estende Query. |
JobFailed |
Error |
KScript.Queue: un job che ha esaurito i tentativi. JobTimeout estende Timeout. |
Nessun nome di tipo termina con Error: sono tutti errori. (QueryError e ConnectionError ora sono Query e Connection, e catch QueryError lo segnala.)
Un nome in catch o throw che non è né dichiarato né predefinito funziona ancora (come una specie di Error), ma l'editor avvisa (KS5011), perché di solito è un refuso.