forked from ebhomengo/niki
1
0
Fork 0
niki/pkg/http_msg/mapper.go

50 lines
1006 B
Go
Raw Normal View History

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