Skip to content

Error types

Every error is an object of a class under Throwable. The list of classes is short and fixed. Each built-in failure throws one of them.

The error classes

Every error in Novis is an object of a class under Throwable, and the whole tree is short. There is no Exception and no Error.

LogicError means a bug in your own program, such as a match with no arm for the value it was given. RuntimeError means the world said no: a missing array key, a value that cannot be converted, a file you are not allowed to read. IOError, ParseError, TimeoutError and RecursionError are kinds of RuntimeError. ArithmeticError is its own branch, for division by zero and for a number that does not fit.

A catch arm also catches every class under the one it names, so catch (Throwable $e) catches everything.

The examples below show which class each common failure throws, how one arm takes a whole branch, and a job that treats a bug and a bad input differently. The last one shows the error for Exception.

Which class a failure throws

<?nvs
// Shows which class each common failure throws. The class tells you what kind
// of problem it is, so you can catch only the kind you can handle.
int $zero = 0;
array<int> $stock = ['mugs' => 4];
mixed $text = 'abc';
// Division by zero is an `ArithmeticError`.
try {
echo 1 / $zero, "\n";
} catch (ArithmeticError $divided) {
echo $divided->message, "\n";
}
// A key that is not in the array is a `RuntimeError`.
try {
echo $stock['plates'], "\n";
} catch (RuntimeError $missing) {
echo $missing->message, "\n";
}
// A value that cannot be converted is a `RuntimeError` as well.
try {
echo $text as int, "\n";
} catch (RuntimeError $bad) {
echo $bad->message, "\n";
}
// A `match` with no arm for the value is a bug in the program, so it is a
// `LogicError`.
try {
echo match ($zero) { 1 => 'one' }, "\n";
} catch (LogicError $noArm) {
echo $noArm->message, "\n";
}
Output
Division by zero
undefined array key `plates`
cannot convert this value to `int`
no `match` arm matched the subject

One arm takes a whole branch

<?nvs
// Shows that a `catch` arm also catches every class under the one it names.
// `IOError`, `ParseError` and `TimeoutError` are kinds of `RuntimeError`.
final class Feed
{
public static function fetch(string $source): tainted string
{
if ($source == 'slow') {
throw new TimeoutError('the feed did not answer in time');
}
if ($source == 'gone') {
throw new IOError('the feed file is missing');
}
return Core\Json::encode(Core\Json::decode($source));
}
}
array<string> $sources = ["{\"ok\": true}", 'slow', 'gone', "{\"ok\": }"];
foreach ($sources as string $source) {
try {
echo Feed::fetch($source), "\n";
} catch (ParseError $bad) {
// The narrow arm goes first. It takes the parse errors and nothing else.
echo 'bad input: ', $bad->message, "\n";
} catch (RuntimeError $other) {
// The wide arm takes the rest of the branch, here a timeout and a
// missing file.
echo 'the feed said no: ', $other->message, "\n";
}
}
Output
{"ok":true}
the feed said no: the feed did not answer in time
the feed said no: the feed file is missing
bad input: Core\Json::decode(): expected value at line 1 column 8

A bug and a bad input

<?nvs
// Shows a job that treats the two halves of the tree differently. A
// `RuntimeError` is bad input, so the job reports the line and carries on. A
// `LogicError` is a bug in the program, so the job stops.
final class Cart
{
public static function total(array<int> $line): int
{
// A field that is not there throws a `RuntimeError`.
int $price = $line['price'];
int $count = $line['count'];
if ($count < 0) {
// A count below zero can only come from our own code.
throw new LogicError('a line with a count below zero');
}
return $price * $count;
}
}
array<array<int>> $lines = [
['price' => 250, 'count' => 2],
['price' => 400],
['price' => 100, 'count' => 0 - 1],
];
int $sum = 0;
foreach ($lines as array<int> $line) {
try {
$sum = $sum + Cart::total($line);
} catch (RuntimeError $input) {
echo 'skipped a line: ', $input->message, "\n";
} catch (LogicError $bug) {
echo 'stopping, this is a bug: ', $bug->message, "\n";
break;
}
}
echo 'total ', $sum, "\n";
Output
skipped a line: undefined array key `count`
stopping, this is a bug: a line with a count below zero
total 500

Exception is not a class

<?nvs
// Shows that `Exception` does not exist. Extend `RuntimeError` or
// `LogicError` instead.
// proof: compile-error
class ConfigError extends Exception
{
}
Output
error[E0303]: `Exception` is not declared
--> 04-exception-is-not-a-class.nvs:6:27
|
6 | class ConfigError extends Exception
| ^^^^^^^^^ no matching declaration
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

Exception and Error are not declared. class ConfigError extends Exception, catch (Error $e) and new Exception("…") are each the error E0303. Write Throwable, LogicError or RuntimeError.

Throwable is a class. You can create one with new Throwable("…"), and you can extend it directly.

ArithmeticError extends Throwable, not RuntimeError. A catch (RuntimeError $e) clause does not catch it. These are the messages it has:

  • Division by zero gives Division by zero.
  • % by zero gives Modulo by zero.
  • An int addition past the largest int gives Integer addition overflowed.
  • 2.5 as int gives `cannot convert float 2.5 to int . A float with a fraction does not convert to int`.

Your own class can extend any class in the tree, ArithmeticError and ParseError too. A class that extends ParseError has issues, and the list is empty. A class in the tree may be final or abstract.

Core\Test\Failure is the class of a failed assertion. It extends Throwable directly, and your own class cannot extend it: that is the error E0303.

Core\Script::finish() ends the program, and no catch catches it. A finally block still runs.

Class Extends Thrown for
Throwable the top class. catch (Throwable $e) catches every error
LogicError Throwable a bug in the program: a match with no arm, a wrong argument
RuntimeError Throwable a problem outside the program: a missing key, a value that cannot be converted, a missing permission
IOError RuntimeError a file, network or process failure
ParseError RuntimeError input that does not have the expected format, such as bad JSON
TimeoutError RuntimeError a time limit that passed
RecursionError RuntimeError a call stack that is too deep
ArithmeticError Throwable division by zero, a number too large for int, a float with a fraction converted to int
Core\Cli\NotInteractive RuntimeError a prompt with no terminal to read from and no default
Core\Db\DbError RuntimeError a database that does not accept a query or a commit. A failed connection is an IOError
Core\Db\RolledBack RuntimeError a transaction that your own code rolled back
Core\Ldap\LdapError RuntimeError a directory server that does not accept an operation, or that cannot be reached
Core\DeprecatedError LogicError a use of deprecated code, when [errors] deprecated is "throw"
RevokedObjectError LogicError a use of an object after revoke() was called on it
ExtensionError RuntimeError an extension that crashed

The page of every Core method lists the classes it throws. So a catch can name exactly the class it expects.

Properties

You read a caught error through its properties. There are no accessor methods.

getMessage(), getPrevious(), getTrace(), getFile(), getLine() and getCode() do not exist. Write $e->message instead.

Every error has the same four properties. message is the text it was created with. previous is the error that caused it, or null. backtrace is one line per function the throw came out of, innermost first. location is the file and the line of the throw. A ParseError adds issues, one entry per problem the parser found, each with a path and a message.

Good to know: there is no error code anywhere. The class of the error is what says what kind of problem it is.

The examples below show where a throw came from, the list of problems in a parse error, and one log line built out of a caught error. The last one shows the error for getMessage().

Where a throw came from

<?nvs
// Shows the two properties that say where an error came from. `location` is the
// file and the line of the `throw`. `backtrace` has one line per function the
// throw came out of, the innermost one first.
final class Prices
{
public static function of(string $item): int
{
throw new RuntimeError('no price for ' . $item);
}
public static function totalOf(string $item): int
{
return Prices::of($item) * 2;
}
}
try {
echo Prices::totalOf('blue mug'), "\n";
} catch (RuntimeError $failed) {
echo $failed->message, "\n";
echo 'thrown at ', $failed->location, "\n";
foreach ($failed->backtrace as string $frame) {
echo ' ', $frame, "\n";
}
}
Output
no price for blue mug
thrown at docs/examples/lang/errors/properties-not-accessors/01-where-a-throw-came-from.nvs:10
Prices::of() at docs/examples/lang/errors/properties-not-accessors/01-where-a-throw-came-from.nvs:10
Prices::totalOf() at docs/examples/lang/errors/properties-not-accessors/01-where-a-throw-came-from.nvs:15

Every problem in one list

<?nvs
// Shows the extra property of a `ParseError`. `issues` has one entry per
// problem the parser found. This form has two bad fields, and both of them are
// in the list.
array<string> $form = ['name' => 'Ada', 'age' => 'not a number', 'active' => 'yes'];
try {
Core\Arr::shapeAs<{ name: string, age: int, active: bool }>($form);
echo "the form is good\n";
} catch (ParseError $bad) {
echo $bad->message, "\n";
foreach ($bad->issues as ({ path: string, message: string }) $issue) {
// `path` names the field, and `message` says what is wrong with it.
echo ' ', $issue->path, ': ', $issue->message, "\n";
}
}
Output
Core\Arr::shapeAs(): 2 value(s) of `$shape{active,age,name}` did not match
active: expected bool, found a string
age: expected int, found a string

One log line for a failure

<?nvs
// Shows one log line built out of a caught error. It says what went wrong,
// where it was thrown, and which error caused it. The chain is followed to the
// first cause.
class CheckoutFailed extends RuntimeError
{
public function constructor(string $message, ?Throwable $cause)
{
parent::constructor($message, { previous: $cause });
}
}
final class Checkout
{
public static function pay(string $order): string
{
try {
throw new TimeoutError('the payment service did not answer');
} catch (TimeoutError $slow) {
throw new CheckoutFailed('order ' . $order . ' was not paid', $slow);
}
}
}
try {
echo Checkout::pay('4021'), "\n";
} catch (Throwable $failed) {
// A message can contain text from the input, so it is `tainted string`.
tainted string $line = $failed->message . ' at ' . $failed->location;
var $cause = $failed->previous;
bool $more = true;
while ($more) {
// `previous` is `null` at the end of the chain. So the code copies it
// into a variable and checks it before it reads `message`.
var $here = $cause;
if ($here == null) {
$more = false;
} else {
$line = $line . ', caused by: ' . $here->message;
$cause = $here->previous;
}
}
echo $line, "\n";
echo 'frames: ', Core\Arr::count($failed->backtrace), "\n";
}
Output
order 4021 was not paid at docs/examples/lang/errors/properties-not-accessors/03-one-log-line-for-a-failure.nvs:21, caused by: the payment service did not answer
frames: 1

Getmessage does not exist

<?nvs
// Shows that `getMessage()` does not exist. The error tells you to read the
// `message` property instead.
// proof: compile-error
try {
throw new LogicError('boom');
} catch (Throwable $e) {
echo $e->getMessage();
}
Output
error[E0405]: `Throwable` has no method named `getMessage`
--> 04-getmessage-does-not-exist.nvs:9:10
|
9 | echo $e->getMessage();
| ^^ referenced here
= help: an exception has properties and no accessor methods. Write `->message`. The properties are `message`, `previous`, `backtrace`, `location`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

getMessage(), getPrevious(), getTrace(), getTraceAsString(), getFile(), getLine() and getCode() are each the error E0405. The help names the property to read instead. For getCode() it lists the four properties, because there is no error code. $e->code is the error E0405 too.

All four properties are readonly. $e->message = "…" is the error E0782.

location is the empty string until the object is thrown. When the same object is thrown a second time, location changes to the line of the second throw.

backtrace has one line for each method the throw left. A throw in the top-level code of a file has one line, <script>() at main.nvs:2. An object that was never thrown has an empty backtrace.

previous is a ?Throwable. $e->previous->message is the error E0459, because previous may be null. Write $e->previous?->message.

issues exists on ParseError and its subclasses. On any other class, $e->issues is the error E0405. A ParseError that your own code creates has an empty issues list.

Core\Debug::dump($e) prints the four properties. echo $e is the error E0412, and Core\Json::encode($e) throws a RuntimeError. Build the text from $e->message and the other properties.

Core\Db\DbError also has kind, sql and serverMessage, and Core\Db\RolledBack has reason. Core\Ldap\LdapError has kind and code.

Your own error class

Every error is built the same way: new with a message, and an optional second argument naming the error that caused this one.

You can write an error class of your own. It extends Throwable or any class under it. A class that writes no constructor uses the one it inherits, so new OutOfStock("no mugs left") works with nothing else to write. A class that wants more can write its own constructor, add properties, and pass the message on with parent::constructor($message).

A message is always required. new RuntimeError() does not compile.

Good to know: both arguments have names, so you can write new RuntimeError(message: "the server said no") and read the call without counting positions.

The examples below show an error class of your own, one that adds properties in its own constructor, and a loader that keeps the error it caught as the cause of the error it throws.

Your own error class

<?nvs
// Shows how to write an error class of your own. The class extends `Throwable`
// and writes no constructor, so it uses the one it inherits. You pass a message
// to `new` and nothing else.
class OutOfStock extends Throwable
{
}
final class Warehouse
{
public static function pack(string $item, int $inStock): string
{
if ($inStock == 0) {
throw new OutOfStock('no ' . $item . ' left');
}
return 'packed one ' . $item;
}
}
try {
// This prints `packed one blue mug`.
echo Warehouse::pack('blue mug', 4), "\n";
echo Warehouse::pack('red mug', 0), "\n";
} catch (OutOfStock $empty) {
// `message` is the text you passed to `new`. This prints `no red mug left`.
echo $empty->message, "\n";
}
// The message may also be passed by name.
try {
throw new OutOfStock(message: 'the shelf is empty');
} catch (OutOfStock $shelf) {
echo $shelf->message, "\n";
}
Output
packed one blue mug
no red mug left
the shelf is empty

A constructor of its own

<?nvs
// Shows an error class that writes its own constructor. It adds two properties
// and passes the message to the class it extends.
class HttpError extends RuntimeError
{
// `public int $status` and `public string $url` declare the properties and
// fill them from the arguments in one step.
public function constructor(string $message, public int $status, public string $url)
{
parent::constructor($message);
}
}
final class Api
{
public static function get(string $url, int $status): string
{
if ($status >= 400) {
throw new HttpError('the server said no', $status, $url);
}
return 'body of ' . $url;
}
}
try {
echo Api::get('/health', 200), "\n";
echo Api::get('/orders/91', 404), "\n";
} catch (HttpError $failed) {
// This prints `404 /orders/91: the server said no`.
echo $failed->status, ' ', $failed->url, ': ', $failed->message, "\n";
}
// `HttpError` extends `RuntimeError`, so a `RuntimeError` arm catches it too.
try {
echo Api::get('/orders/92', 503), "\n";
} catch (RuntimeError $any) {
echo 'as a runtime error: ', $any->message, "\n";
}
Output
body of /health
404 /orders/91: the server said no
as a runtime error: the server said no

Say which error caused it

<?nvs
// Shows how one error names the error that caused it. A settings loader catches
// the error from the JSON reader and throws its own, with the first one kept as
// the cause. The person reading the log then sees both.
class ConfigError extends RuntimeError
{
public function constructor(string $message, public string $file, ?Throwable $cause)
{
// `{ previous: $cause }` is the options bag of the inherited constructor.
parent::constructor($message, { previous: $cause });
}
}
final class Settings
{
public static function read(string $file, string $text): mixed
{
try {
return Core\Json::decode($text);
} catch (ParseError $bad) {
throw new ConfigError('cannot start without ' . $file, $file, $bad);
}
}
}
try {
echo Core\Json::encode(Settings::read('app.json', "{\"port\": 8080}")), "\n";
echo Core\Json::encode(Settings::read('cache.json', "{\"port\": }")), "\n";
} catch (ConfigError $stop) {
echo $stop->message, "\n";
echo 'the file is ', $stop->file, "\n";
// `previous` is the error that was caught inside `read`.
echo 'caused by: ', $stop->previous?->message ?? 'nothing', "\n";
}
Output
{"port":8080}
cannot start without cache.json
the file is cache.json
caused by: Core\Json::decode(): expected value at line 1 column 10

Details

The message must be a string. new RuntimeError(5) is the error E0401. A tainted string is the error E0401 too, so check text from outside the program before you put it in a message.

previous takes a Throwable or null. Another type is the error E0401. Any other option, such as { cause: $e }, is the error E0454, and its help lists previous.

With names, the arguments may come in any order: new RuntimeError(options: { previous: $e }, message: "…"). A subclass that writes no constructor accepts the names too.

A subclass with its own constructor must call parent::constructor(...) on every path. A path without the call is the error E0410. parent::constructor() with no message is the error E0402.

A subclass may add properties with a default value, such as public int $status = 500;, without a constructor of its own.

Core\Script::finish() throws Core\Script\Finished. This class is not under Throwable, so no catch catches it. Every finally block still runs.

<?nvs
// `Core\Script::finish()` ends the program. It runs every `finally` block on the way out.
// No `catch` block catches it, not even a `catch` for `Throwable`.
try {
echo "writing the report\n";
Core\Script::finish();
} catch (Throwable $error) {
echo 'caught: ', $error->message, "\n";
} finally {
echo "closing the report file\n";
}
echo "this line does not print\n";
Output
writing the report
closing the report file
  • Do read $e->message. getMessage() and the other get...() methods do not exist.
  • Do pass the caught error as { previous: $e } when you throw a new one.
  • Do extend RuntimeError for a problem outside the program, and LogicError for a bug.
  • Don’t write Exception or Error. They do not exist.
  • Don’t catch Throwable when you expect one kind of failure. Name that class.