Introduce custom errors for player handling

Custom errors for malformed/nonexistent player IDs as well as a player
not having a high enough balance for the money requested.

This will allow me to encode more information in the errors, for
callers to use.  I'm generally of the opinion that callers should be
checking error conditions before calling these functions, but per
Murphy's law it would be nice to have more information in the error
message.
This commit is contained in:
2025-02-15 15:40:56 +00:00
parent 4ded442dd4
commit 24b07f9166
2 changed files with 27 additions and 3 deletions

View File

@@ -55,6 +55,8 @@
(:export
:player
:players
:error-player-nonexistent
:error-player-broke
:player-id :player-balance :player-hand
:player-exists? :player-bankrupt? :player-can-bet?
:player-pay

View File

@@ -28,6 +28,25 @@
(deftype players () 'list)
(define-condition error-player-nonexistent (error)
((id :initarg :id :reader id))
(:report
(lambda (err stream)
(format stream "Player [~a] is non-existent or malformed"
(id err)))))
(define-condition error-player-broke (error)
((id :initarg :id :reader id)
(balance :initarg :balance :reader balance)
(required :initarg :required :reader required))
(:report
(lambda (err stream)
(format stream "Player [~a] has balance $~a but $~a requested."
(id err)
(balance err)
(required err)))))
(fn player-id (player) (-> (player) fixnum)
(car player))
@@ -50,10 +69,13 @@
(let ((p (assoc id players)))
(cond
((not (typep p 'player))
(error "Player [~a] does not exist."))
(error 'error-player-nonexistent
:id id))
((not (player-can-bet? amount p))
(error "Player [~a] has $~a but needs to pay ~a."
id (player-balance p) amount))
(error 'error-player-broke
:id id
:balance (player-balance p)
:required amount))
(t
(destructuring-bind (id balance cards) p
(setf (cdr (assoc id players))