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.
Your own errors
Section titled “Your own errors”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";green tea404: no product 8unknownThe 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.
Two kinds of error
Section titled “Two kinds of error”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.
Failures you cannot catch
Section titled “Failures you cannot catch”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 and don’t
Section titled “Do and don’t”- 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
previouswhen you throw a new error from acatchblock. - Don’t catch an error only to ignore it. Use a
catchexpression 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.
