mirror of
https://github.com/m1k1o/neko.git
synced 2025-05-19 12:07:06 +02:00
API resiolution with error handling.
This commit is contained in:
parent
0c40eda36b
commit
d48b857dfe
2 changed files with 81 additions and 27 deletions
60
internal/api/utils/error.go
Normal file
60
internal/api/utils/error.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/render"
|
||||
)
|
||||
|
||||
//--
|
||||
// Error response payloads & renderers
|
||||
//--
|
||||
|
||||
// ErrResponse renderer type for handling all sorts of errors.
|
||||
//
|
||||
// In the best case scenario, the excellent github.com/pkg/errors package
|
||||
// helps reveal information on the error, setting it on Err, and in the Render()
|
||||
// method, using it to set the application-specific error code in AppCode.
|
||||
type ErrResponse struct {
|
||||
Err error `json:"-"` // low-level runtime error
|
||||
HTTPStatusCode int `json:"-"` // http response status code
|
||||
|
||||
StatusText string `json:"status"` // user-level status message
|
||||
AppCode int64 `json:"code,omitempty"` // application-specific error code
|
||||
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
|
||||
}
|
||||
|
||||
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
|
||||
render.Status(r, e.HTTPStatusCode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func ErrMessage(HTTPStatusCode int, StatusText string) render.Renderer {
|
||||
return &ErrResponse{
|
||||
HTTPStatusCode: HTTPStatusCode,
|
||||
StatusText: StatusText,
|
||||
}
|
||||
}
|
||||
|
||||
func ErrInvalidRequest(err error) render.Renderer {
|
||||
return &ErrResponse{
|
||||
Err: err,
|
||||
HTTPStatusCode: 400,
|
||||
StatusText: "Invalid request.",
|
||||
ErrorText: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
func ErrRender(err error) render.Renderer {
|
||||
return &ErrResponse{
|
||||
Err: err,
|
||||
HTTPStatusCode: 422,
|
||||
StatusText: "Error rendering response.",
|
||||
ErrorText: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
var ErrNotFound = &ErrResponse{
|
||||
HTTPStatusCode: 404,
|
||||
StatusText: "Resource not found.",
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue