From 092a4b308f5707935e5024d01b122aa95704f011 Mon Sep 17 00:00:00 2001 From: mohammad mahdi rezaei Date: Mon, 18 Dec 2023 17:38:07 +0330 Subject: [PATCH] feat(pkg): added err message and http message mapper --- pkg/errmsg/message.go | 6 ++++++ pkg/httpmsg/mapper.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 pkg/errmsg/message.go create mode 100644 pkg/httpmsg/mapper.go diff --git a/pkg/errmsg/message.go b/pkg/errmsg/message.go new file mode 100644 index 0000000..2d67a71 --- /dev/null +++ b/pkg/errmsg/message.go @@ -0,0 +1,6 @@ +package errmsg + +const ( + ErrorMsgNotFound = "record not found" + ErrorMsgSomethingWentWrong = "something went wrong" +) diff --git a/pkg/httpmsg/mapper.go b/pkg/httpmsg/mapper.go new file mode 100644 index 0000000..114fd3a --- /dev/null +++ b/pkg/httpmsg/mapper.go @@ -0,0 +1,41 @@ +package httpmsg + +import ( + "git.gocasts.ir/ebhomengo/niki/pkg/errmsg" + "git.gocasts.ir/ebhomengo/niki/pkg/richerror" + "net/http" +) + +func Error(err error) (message string, code int) { + switch err.(type) { + case richerror.RichError: + re := err.(richerror.RichError) + msg := re.Message() + + code := mapKindToHTTPStatusCode(re.Kind()) + + // we should not expose unexpected error messages + if code >= 500 { + msg = errmsg.ErrorMsgSomethingWentWrong + } + + return msg, code + default: + return err.Error(), http.StatusBadRequest + } +} + +func mapKindToHTTPStatusCode(kind richerror.Kind) int { + switch kind { + case richerror.KindInvalid: + return http.StatusUnprocessableEntity + case richerror.KindNotFound: + return http.StatusNotFound + case richerror.KindForbidden: + return http.StatusForbidden + case richerror.KindUnexpected: + return http.StatusInternalServerError + default: + return http.StatusBadRequest + } +}