niki/pkg/http_msg/mapper.go

50 lines
1007 B
Go

package httpmsg
import (
"errors"
"net/http"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
// TODO: this temperary to ignore linter error.(maggic number).
const (
internalStatus = 500
)
func Error(err error) (message string, code int) {
var re *richerror.RichError
if !errors.As(err, &re) {
return err.Error(), http.StatusBadRequest
}
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:
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
}
}