2024-04-06 21:11:22 +07:00
|
|
|
package errs
|
|
|
|
|
2024-04-26 10:51:09 +07:00
|
|
|
import (
|
|
|
|
"errors"
|
2024-05-27 14:29:09 +07:00
|
|
|
"net/http"
|
2024-04-26 10:51:09 +07:00
|
|
|
)
|
2024-04-06 21:11:22 +07:00
|
|
|
|
|
|
|
func FindCodeOrDefault(err error, def int) int {
|
2024-04-26 10:51:09 +07:00
|
|
|
if coder, ok := err.(interface{ GetCode() int }); ok {
|
|
|
|
code := coder.GetCode()
|
|
|
|
if code != 0 {
|
|
|
|
return code
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for unwrap := errors.Unwrap(err); unwrap != nil; unwrap = errors.Unwrap(unwrap) {
|
|
|
|
if coder, ok := unwrap.(interface{ GetCode() int }); ok {
|
2024-04-06 21:11:22 +07:00
|
|
|
code := coder.GetCode()
|
|
|
|
if code != 0 {
|
2024-04-24 21:57:13 +07:00
|
|
|
return code
|
2024-04-06 21:11:22 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-04-24 21:57:13 +07:00
|
|
|
|
2024-04-06 21:11:22 +07:00
|
|
|
return def
|
|
|
|
}
|
2024-04-24 21:57:13 +07:00
|
|
|
|
|
|
|
func FindMessage(err error) string {
|
2024-04-26 10:51:09 +07:00
|
|
|
if messager, ok := err.(interface{ GetMessage() string }); ok {
|
|
|
|
message := messager.GetMessage()
|
|
|
|
if message != "" {
|
|
|
|
return message
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for unwrap := errors.Unwrap(err); unwrap != nil; unwrap = errors.Unwrap(unwrap) {
|
|
|
|
if messager, ok := unwrap.(interface{ GetMessage() string }); ok {
|
2024-04-24 21:57:13 +07:00
|
|
|
message := messager.GetMessage()
|
|
|
|
if message != "" {
|
|
|
|
return message
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return err.Error()
|
|
|
|
}
|
2024-04-24 22:26:04 +07:00
|
|
|
|
|
|
|
func HTTPMessage(err error) (code int, message string) {
|
|
|
|
code = FindCodeOrDefault(err, 500)
|
|
|
|
if code >= 500 {
|
|
|
|
return code, err.Error()
|
|
|
|
}
|
2024-04-26 10:51:09 +07:00
|
|
|
message = FindMessage(err)
|
|
|
|
return code, message
|
2024-04-24 22:26:04 +07:00
|
|
|
}
|
2024-05-27 14:29:09 +07:00
|
|
|
|
|
|
|
func HasCode(err error, code int) bool {
|
|
|
|
return FindCodeOrDefault(err, http.StatusInternalServerError) == code
|
|
|
|
}
|
|
|
|
|
|
|
|
func Source(err error) error {
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if _, ok := err.(Error); !ok {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for unwrap := errors.Unwrap(err); unwrap != nil; unwrap = errors.Unwrap(unwrap) {
|
|
|
|
if _, ok := unwrap.(Error); !ok {
|
|
|
|
return unwrap
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|