Skip to content

Errors

Novis uses exceptions for errors. A method throws an error. The code that can handle the error catches it. Throwing an error is fast, so you can use errors on a busy server too.

Give each kind of failure in your application its own class. Extend RuntimeError for a failure that can happen in a correct program, such as a missing record:

<?nvs
// This program throws its own error class and handles it in one place.
class NotFound extends RuntimeError
{
public function constructor(string $message)
{
parent::constructor($message);
}
}
class Products
{
public static function name(int $id): string
{
if ($id != 7) {
throw new NotFound('no product ' . $id);
}
return 'green tea';
}
}
// One `try` block handles the error for the whole request.
try {
echo Products::name(7), "\n";
echo Products::name(8), "\n";
} catch (NotFound $error) {
echo '404: ', $error->message, "\n";
}
// A `catch` expression gives a default value in one line.
string $name = Products::name(9) catch (NotFound $e) => 'unknown';
echo $name, "\n";
Output
green tea
404: no product 8
unknown

The first try block catches the error from Products::name(8). The catch expression after Products::name(9) gives the default value "unknown" in one line.

RuntimeError is for a problem the program cannot prevent: a missing file, a network failure or bad input. LogicError is for a mistake in the code, such as a method called at the wrong time. Catch a RuntimeError and handle it. A LogicError is a bug, so fix the code.

A request that goes over a limit stops at once. This is not an exception, so no catch block runs. The server writes the failure to its log, and the other requests keep running. Core\Fatal::onLimit registers a handler that runs when this happens.

  • Do create one error class for each kind of failure that a caller handles in its own way.
  • Do catch errors in one place for each request, and set the status there.
  • Do pass the original error as previous when you throw a new error from a catch block.
  • Don’t catch an error only to ignore it. Use a catch expression with a clear default value.
  • Don’t show the message of an unexpected error to the client. Write it to the log.

Read more in Syntax: error types and Syntax: the catch expression.