2023-12-18 14:08:07 +00:00
|
|
|
package httpmsg
|
|
|
|
|
|
|
|
import (
|
2024-01-01 07:22:14 +00:00
|
|
|
"errors"
|
2023-12-18 14:08:07 +00:00
|
|
|
"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
|
|
|
)
|
|
|
|
|
2024-01-01 07:22:14 +00:00
|
|
|
// TODO: this temperary to ignore linter error.(maggic number).
|
|
|
|
const (
|
|
|
|
internalStatus = 500
|
|
|
|
)
|
2023-12-18 14:08:07 +00:00
|
|
|
|
2024-01-01 07:22:14 +00:00
|
|
|
func Error(err error) (message string, code int) {
|
2024-01-05 12:21:10 +00:00
|
|
|
var re richerror.RichError
|
2024-01-01 07:22:14 +00:00
|
|
|
if !errors.As(err, &re) {
|
2023-12-18 14:08:07 +00:00
|
|
|
return err.Error(), http.StatusBadRequest
|
|
|
|
}
|
2024-01-01 07:22:14 +00:00
|
|
|
msg := re.Message()
|
|
|
|
code = mapKindToHTTPStatusCode(re.Kind())
|
|
|
|
// we should not expose unexpected error messages
|
|
|
|
if code >= internalStatus {
|
|
|
|
msg = errmsg.ErrorMsgSomethingWentWrong
|
|
|
|
}
|
|
|
|
|
|
|
|
return msg, code
|
2023-12-18 14:08:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func mapKindToHTTPStatusCode(kind richerror.Kind) int {
|
|
|
|
switch kind {
|
|
|
|
case richerror.KindInvalid:
|
2024-01-01 07:22:14 +00:00
|
|
|
|
2023-12-18 14:08:07 +00:00
|
|
|
return http.StatusUnprocessableEntity
|
|
|
|
case richerror.KindNotFound:
|
2024-01-01 07:22:14 +00:00
|
|
|
|
2023-12-18 14:08:07 +00:00
|
|
|
return http.StatusNotFound
|
|
|
|
case richerror.KindForbidden:
|
2024-01-01 07:22:14 +00:00
|
|
|
|
2023-12-18 14:08:07 +00:00
|
|
|
return http.StatusForbidden
|
|
|
|
case richerror.KindUnexpected:
|
2024-01-01 07:22:14 +00:00
|
|
|
|
2023-12-18 14:08:07 +00:00
|
|
|
return http.StatusInternalServerError
|
|
|
|
default:
|
2024-01-01 07:22:14 +00:00
|
|
|
|
2023-12-18 14:08:07 +00:00
|
|
|
return http.StatusBadRequest
|
|
|
|
}
|
|
|
|
}
|