Skip to content

Commit

Permalink
refactor responses and codes
Browse files Browse the repository at this point in the history
  • Loading branch information
vladyslav2 committed Dec 9, 2023
1 parent 51904ec commit b1cc712
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
15 changes: 10 additions & 5 deletions server/response/codes.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package response

var (
BadRequestMsg = map[string][]string{"__error__": {"bad request"}}
// BadAuth signalizes lack of token or other authorization data
NotAuthorizedMsg = map[string][]string{"__error__": {"authorization error"}}
// InternalError server side error
InternalErrMsg = map[string][]string{"__error__": {"internal/server error"}}
// MsgBadRequest used to indicate error in incoming data
MsgBadRequest = map[string][]string{"__error__": {"bad request"}}
// MsgNotFound typically used when element haven't been found
MsgNotFound = map[string][]string{"__error__": {"not found"}}
// MsgUnauthorized signalizes lack of token or other authorization data
MsgUnauthorized = map[string][]string{"__error__": {"authorization error"}}
// MsgForbidden used when user does not have any permissions to perform action
MsgForbidden = map[string][]string{"__error__": {"forbidden error"}}
// MsgInternalErr server side error
MsgInternalErr = map[string][]string{"__error__": {"internal/server error"}}
)
26 changes: 21 additions & 5 deletions server/response/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,34 @@ func (r Error) Unwrap() error {
return r.Err
}

func BadRequest(err error) Error {
// BadRequest shortcut to return http.StatusBadRequest with custom error and msg
func BadRequest(err error, msg string) Error {
if err == nil {
err = fmt.Errorf("")
}
finalMsg := map[string][]string{"__error__": {msg}}
if msg == "" {
finalMsg = MsgBadRequest
}
return New(
err,
http.StatusBadRequest,
BadRequestMsg,
finalMsg,
)
}

func BadRequestMsg(msg string) Error {
// NotFound shortcut to return http.StatusNotFound with custom error and msg
func NotFound(err error, msg string) Error {
if err == nil {
err = fmt.Errorf("")
}
finalMsg := map[string][]string{"__error__": {msg}}
if msg == "" {
finalMsg = MsgNotFound
}
return New(
fmt.Errorf(""),
err,
http.StatusBadRequest,
map[string][]string{"__error__": {msg}},
finalMsg,
)
}

0 comments on commit b1cc712

Please sign in to comment.