Skip to content

Instantly share code, notes, and snippets.

@2garryn
Created October 30, 2018 12:13
Show Gist options
  • Save 2garryn/712ff48bfd4f50a27ddf90b45736c0ba to your computer and use it in GitHub Desktop.
Save 2garryn/712ff48bfd4f50a27ddf90b45736c0ba to your computer and use it in GitHub Desktop.
package vkerr
import (
"encoding/json"
"vkanalyze/libs/log"
"github.com/jackc/pgx"
)
const NotFound = 100
const AlreadyExist = 101
const Forbidden = 102
const NotAllAdded = 103
const DeleteFirstly = 104
// System errors
const InternalError = 1
const NotImplemented = 2
// JSON validation errors 200..300
const JsonBadBody = 10001
// Auth error
const AuthErrorUserNotFound = 20001
// GroupErrors
const GroupNotFound = 30001
type Err struct {
Code int
Message string
}
func (e Err) Error() string {
return e.Message
}
func (e Err) ToHttpCode() int {
switch e.Code {
case JsonBadBody:
return 400
case AlreadyExist:
return 409
case InternalError:
return 500
case NotFound:
return 404
case Forbidden:
return 403
case NotAllAdded:
return 500
}
return 200
}
func (e Err) ToHttpError() []byte {
st := struct {
Code int `json:"code"`
Message string `json:"message"`
}{
Code: e.Code,
Message: e.Message,
}
b, _ := json.Marshal(st)
return b
}
func E(code int, message string) error {
return Err{
Code: code,
Message: message,
}
}
func ToBytes(e error) []byte {
myerr, ok := e.(Err)
if ok {
return myerr.ToHttpError()
} else {
newE := E(1, "Internal error").(Err)
return newE.ToHttpError()
}
}
func GetCode(e error) int {
myerr, ok := e.(Err)
if ok {
return myerr.Code
} else {
return InternalError
}
}
func PgE(err error) error {
if err == nil {
return nil
}
pgerr, _ := err.(pgx.PgError)
switch pgerr.Code {
case "23505":
return Err{AlreadyExist, "Already exist"}
default:
log.Log.Error("Database internal error ", err, pgerr.Message)
return Err{InternalError, ""}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment