This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
const (
|
||||
CodeInvalidRequest Code = "invalid_request"
|
||||
CodeUnauthorized Code = "unauthorized"
|
||||
CodeNotFound Code = "not_found"
|
||||
CodeConflict Code = "conflict"
|
||||
CodePayloadTooLarge Code = "payload_too_large"
|
||||
CodeUnsupportedMedia Code = "unsupported_media_type"
|
||||
CodeRateLimited Code = "rate_limited"
|
||||
CodeUnavailable Code = "unavailable"
|
||||
CodeInternal Code = "internal_error"
|
||||
)
|
||||
|
||||
type Body struct {
|
||||
Code Code `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type Envelope struct {
|
||||
Error Body `json:"error"`
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code Code
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string { return e.Msg }
|
||||
|
||||
func New(status int, code Code, msg string) *AppError {
|
||||
return &AppError{Status: status, Code: code, Msg: msg}
|
||||
}
|
||||
|
||||
func InvalidRequest(msg string) *AppError { return New(http.StatusBadRequest, CodeInvalidRequest, msg) }
|
||||
func Unauthorized(msg string) *AppError { return New(http.StatusUnauthorized, CodeUnauthorized, msg) }
|
||||
func NotFound(msg string) *AppError { return New(http.StatusNotFound, CodeNotFound, msg) }
|
||||
func Conflict(msg string) *AppError { return New(http.StatusConflict, CodeConflict, msg) }
|
||||
func PayloadTooLarge(msg string) *AppError {
|
||||
return New(http.StatusRequestEntityTooLarge, CodePayloadTooLarge, msg)
|
||||
}
|
||||
func UnsupportedMedia(msg string) *AppError {
|
||||
return New(http.StatusUnsupportedMediaType, CodeUnsupportedMedia, msg)
|
||||
}
|
||||
func Unavailable(msg string) *AppError {
|
||||
return New(http.StatusServiceUnavailable, CodeUnavailable, msg)
|
||||
}
|
||||
func Internal(msg string) *AppError { return New(http.StatusInternalServerError, CodeInternal, msg) }
|
||||
|
||||
// Write отдаёт ошибку в формате контракта: {"error":{"code","message","request_id"}}.
|
||||
func Write(w http.ResponseWriter, requestID string, err *AppError) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(err.Status)
|
||||
_ = json.NewEncoder(w).Encode(Envelope{Error: Body{Code: err.Code, Message: err.Msg, RequestID: requestID}})
|
||||
}
|
||||
Reference in New Issue
Block a user