niki/pkg/http_msg/mapper.go

53 lines
1.1 KiB
Go
Raw Normal View History

package httpmsg
import (
2024-01-01 07:22:14 +00:00
"errors"
"fmt"
"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 {
// TODO - we have to use log instead of print
fmt.Println("internal error: ", msg)
2024-01-01 07:22:14 +00:00
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
}
}