memos/api/e/error.go

51 lines
845 B
Go
Raw Normal View History

2021-12-09 22:02:57 +08:00
package e
2021-12-08 23:43:14 +08:00
import (
"encoding/json"
"net/http"
)
type ServerError struct {
Code int
Message string
}
type ErrorResponse struct {
2021-12-09 22:02:57 +08:00
Succeed bool `json:"succeed"`
Message string `json:"message"`
StatusCode int `json:"statusCode"`
Data interface{} `json:"data"`
2021-12-08 23:43:14 +08:00
}
func getServerError(err string) ServerError {
code, exists := Codes[err]
2021-12-09 22:02:57 +08:00
println(err)
2021-12-08 23:43:14 +08:00
if !exists {
2021-12-09 22:02:57 +08:00
err = "BAD_REQUEST"
2021-12-08 23:43:14 +08:00
code = 40000
}
return ServerError{
Code: code,
Message: err,
}
}
2021-12-09 22:02:57 +08:00
func ErrorHandler(w http.ResponseWriter, err string, message string) {
2021-12-08 23:43:14 +08:00
serverError := getServerError(err)
res := ErrorResponse{
2021-12-09 22:02:57 +08:00
Succeed: false,
Message: message,
StatusCode: serverError.Code,
Data: nil,
2021-12-08 23:43:14 +08:00
}
statusCode := int(serverError.Code / 100)
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(res)
}