2023-12-18 14:08:07 +00:00
|
|
|
package httpmsg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2023-12-20 15:39:25 +00:00
|
|
|
|
|
|
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
|
|
|
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
|
2023-12-18 14:08:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|