From 9371746887da325a902e9995755667054dfd31d1 Mon Sep 17 00:00:00 2001 From: Loic Guegan Date: Sat, 11 May 2019 08:31:03 +0200 Subject: [PATCH] Improve error handlling --- server/api/api.lisp | 23 +++++++++++++++++------ server/server.lisp | 6 +++--- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/server/api/api.lisp b/server/api/api.lisp index 1e9a74d..6c99ea8 100644 --- a/server/api/api.lisp +++ b/server/api/api.lisp @@ -4,29 +4,40 @@ ((gm :initform (make-instance 'game-manager)))) + +(define-condition bad-request (error) + ((msg + :reader bad-request-msg + :initarg :msg + :initform "Unkown error occurs")) + (:report (lambda (condition stream) (format stream "Bad Request: ~a" (bad-request-msg condition))))) + + ;;; Parse the request and return it as a plist +;;; TODO Check game using game-manager (create the right error condition in gm) (defun parse-request (request) (flet ((normalizer (key) (string-upcase key))) (let* ((p-request (parse request :normalize-all t :keyword-normalizer #'normalizer )) (type (getf p-request :type :not-found))) (cond ((eq type :not-found) - (error "Invalid request: Bad request type")) + (error 'bad-request :msg "No json \"type\" field provided")) ((equal type "update") (progn - (unless (getf p-request :game-id) (error "Invalid request: No game id")) + (unless (getf p-request :game-id) (error 'bad-request :msg "No json \"game-id\" field provided")) (let ((dir (getf p-request :direction :not-found))) - (when (eq :not-found dir) (error "Invalid request: No snake direction provided")) - (unless (or (equal "up" dir) (equal "down" dir) (equal "left" dir) (equal "right" dir) (eq nil dir)) (error "Invalid request: Bad direction")) + (when (eq :not-found dir) (error 'bad-request :msg "No json \"direction\" field provided")) + (unless (or (equal "up" dir) (equal "down" dir) (equal "left" dir) (equal "right" dir) (eq nil dir)) (error 'bad-request :msg "Bad \"direction\" field value")) (cond ((equal dir "up") (setf (getf p-request :direction) :up)) ((equal dir "down") (setf (getf p-request :direction) :down)) ((equal dir "left") (setf (getf p-request :direction) :left)) ((equal dir "right") (setf (getf p-request :direction) :right)))))) ((not (equal type "new-game")) - (error "Invalid request: Unknow request type"))) + (error 'bad-request :msg "Unknown request type"))) p-request))) - + + (defmethod handle-new-game ((api api) data) diff --git a/server/server.lisp b/server/server.lisp index b16bd2d..bf778b1 100644 --- a/server/server.lisp +++ b/server/server.lisp @@ -20,9 +20,9 @@ ;;; The server :D -(defun start (port) - (format t "Server start !~%") - (let ((socket (usocket:socket-listen "127.0.0.1" port))) +(defun start (interface port) + (format t "Server started!~%") + (let ((socket (usocket:socket-listen interface port))) (unwind-protect ; To be sure to close server socket (loop (handle-client (usocket:socket-accept socket :element-type 'character)))