The Basics
Error Handling
Introduction
When you start a new Laravel Bash project, error and exception handling is already configured for you, by set -Eeuo pipefail and two traps.
Strict mode
bootstrap/app.sh turns on Bash's strict mode before anything else:
| Option | Meaning |
|---|---|
-e | Exit when a command fails, like an uncaught exception |
-E | Run the ERR trap inside functions too |
-u | Using a variable that was never set is an error, like strict_types for typos |
-o pipefail | A pipeline fails if any part of it fails, not just the last one |
warning
set -e is ignored inside anything being tested: an if condition, either side of && or ||, and after !. A function that would fail is fine when called as if my_function, and every command inside it carries on regardless. This is documented, and still surprises everyone.
The Exception Handler
Every request sets a trap on ERR, which runs when any command fails:
trap 'http::exception $? "$BASH_COMMAND" $LINENO' ERR
http::exception sets the status to 500, logs the failure, and renders errors.500 with a stack trace. The stack trace comes from caller, a builtin that prints the line, function and file of each frame:
34 whoops routes/web.sh
24 router::dispatch framework/routing.sh
139 http::handle framework/http.sh
5 main bootstrap/handle
See it at /whoops.
HTTP Exceptions
abort 404
abort 403
abort renders resources/views/errors/{status}.blade.sh if it exists, then exits. The EXIT trap sends the response.
Exit codes are exceptions
In Laravel, a failing function throws. In Bash, it returns a number other than 0, and the caller decides what to do:
post=$(Post::find "$1") || abort 404
0 means success, and is the only value of "true" that is falsy everywhere else in computing.