Skip to content

Commit 46f254e

Browse files
committed
docs(errors): added recommendation around errors as values
1 parent 3f729f9 commit 46f254e

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

docs/errors.md

+19-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,22 @@ assert(isPlayerDead(), "player is not dead")
2828
## Throwing an Error vs Logging
2929
Some states may be unexpected, but recoverable. In these cases, it may be preferable to log the state, but still allow the operation to proceed. An example of this would be a player selling items to an NPC. If some of the items were failing to sell, it would be better to log/print the error, while allowing the rest of the items to go through.
3030

31-
Keep in mind what execution will be cancelled by throwing an error and use best judgment to decide whether throwing or logging is the better choice.
31+
Keep in mind what execution will be cancelled by throwing an error and use best judgment to decide whether throwing or logging is the better choice.
32+
33+
## Assertions vs Errors as Values
34+
Assertions cause lua errors to propagate up the stack, forcing callers to handle them via protected calls. While assertions should always be used for unexpected or "impossible" cases, errors as values can be helpful for expected failure cases that we want the caller of the API to handle. This involves returning a success boolean, followed by an optional error code & message. Doing this makes the default behavior of our function fail silently, as it becomes the callers responsibility to decide to handle the error. This can provide a better experience for players as a silent failure may preferable to loud error messages in cases where the player pressed the wrong button for example.
35+
36+
Note that API functions should be idempotent when possible. A no-op result is still considered successful, if the state of the system is the one the caller expects after the function is ran.
37+
38+
### Example Error as Value
39+
```lua
40+
function add(a, b)
41+
if not a or not b then
42+
return nil, {
43+
code = 'missing_required_params',
44+
message = 'either a or b is nil',
45+
}
46+
end
47+
return a + b
48+
end
49+
```

0 commit comments

Comments
 (0)