talent/error.go

71 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"runtime"
)
type Error struct {
Code int `json:"code"`
ID string `json:"id"`
Message string `json:"msg"`
}
func (e Error) Error() string {
return e.Message
}
func (e Error) String() string {
return e.Message
}
func (e Error) Json() []byte {
data, _ := json.Marshal(e)
return data
}
func New(code int, err string, args ...interface{}) *Error {
return &Error{Code: code, Message: fmt.Sprintf(err, args...)}
}
func NewError(code int, err error) *Error {
return &Error{Code: code, Message: err.Error()}
}
func Stack() string {
buf := make([]byte, 1024)
for {
n := runtime.Stack(buf, false)
if n < len(buf) {
return string(buf[:n])
}
buf = make([]byte, 2*len(buf))
}
}
var ErrorNotFound = Error{
Code: http.StatusNotFound,
ID: "ErrorNotFound",
Message: "not found",
}
var ErrorUnauthorized = Error{
Code: http.StatusUnauthorized,
ID: "ErrorUnauthorized",
Message: "unauthorized",
}
var ErrorForbidden = Error{
Code: http.StatusForbidden,
ID: "ErrorForbidden",
Message: "permission denied",
}
var ErrorBadRequest = Error{
Code: http.StatusBadRequest,
ID: "ErrorBadRequest",
Message: "bad request",
}