1
0
mirror of https://github.com/lxc/incus.git synced 2026-02-05 18:45:46 +01:00
Files
incus/shared/api/error.go
JUN JIE NAN ac3082a4f6 shared/api: Simplify code by using modern constructs
Using more modern features of Go, such as:
- conditional assignment -> built-in min or max in go1.21,
- sort.Slice -> slices.Sort in go1.21,
- loop assign map -> maps.Copy in go1.21,
- []byte(fmt.Sprintf...) -> fmt.Appendf(nil,...) in go1.19,
- strings.HasPrefix / strings.TrimPrefix -> strings.CutPrefix in go1.20

Signed-off-by: JUN JIE NAN <nanjunjie@gmail.com>
2025-05-17 12:32:29 -04:00

72 lines
1.7 KiB
Go

package api
import (
"errors"
"fmt"
"net/http"
"slices"
)
// StatusErrorf returns a new StatusError containing the specified status and message.
func StatusErrorf(status int, format string, a ...any) StatusError {
var msg string
if len(a) > 0 {
msg = fmt.Sprintf(format, a...)
} else {
msg = format
}
return StatusError{
status: status,
msg: msg,
}
}
// StatusError error type that contains an HTTP status code and message.
type StatusError struct {
status int
msg string
}
// Error returns the error message or the http.StatusText() of the status code if message is empty.
func (e StatusError) Error() string {
if e.msg != "" {
return e.msg
}
return http.StatusText(e.status)
}
// Status returns the HTTP status code.
func (e StatusError) Status() int {
return e.status
}
// StatusErrorMatch checks if err was caused by StatusError. Can optionally also check whether the StatusError's
// status code matches one of the supplied status codes in matchStatus.
// Returns the matched StatusError status code and true if match criteria are met, otherwise false.
func StatusErrorMatch(err error, matchStatusCodes ...int) (int, bool) {
var statusErr StatusError
if errors.As(err, &statusErr) {
statusCode := statusErr.Status()
if len(matchStatusCodes) <= 0 {
return statusCode, true
}
if slices.Contains(matchStatusCodes, statusCode) {
return statusCode, true
}
}
return -1, false
}
// StatusErrorCheck returns whether or not err was caused by a StatusError and if it matches one of the
// optional status codes.
func StatusErrorCheck(err error, matchStatusCodes ...int) bool {
_, found := StatusErrorMatch(err, matchStatusCodes...)
return found
}