style(backend): improve error handling

This commit is contained in:
2025-10-10 01:37:01 +03:00
parent d124229308
commit b774d2b3c9
4 changed files with 115 additions and 85 deletions
+36 -17
View File
@@ -1,18 +1,20 @@
package domain
import "fmt"
type ErrorCode string
const (
// File errors
ErrFileNotFound ErrorCode = "FILE_NOT_FOUND"
ErrMIMENotSupported ErrorCode = "MIME_NOT_SUPPORTED"
ErrCodeFileNotFound ErrorCode = "FILE_NOT_FOUND"
ErrCodeMIMENotSupported ErrorCode = "MIME_NOT_SUPPORTED"
// Tag errors
ErrTagNotFound ErrorCode = "TAG_NOT_FOUND"
ErrCodeTagNotFound ErrorCode = "TAG_NOT_FOUND"
// General errors
ErrValidation ErrorCode = "VALIDATION_ERROR"
ErrInternal ErrorCode = "INTERNAL_SERVER_ERROR"
ErrCodeBadRequest ErrorCode = "BAD_REQUEST"
ErrCodeInternal ErrorCode = "INTERNAL_SERVER_ERROR"
)
type DomainError struct {
@@ -22,25 +24,42 @@ type DomainError struct {
Details []any `json:"-"`
}
func (e *DomainError) Error() string {
if e.Err != nil {
return e.Message + ": " + e.Err.Error()
}
return e.Message
func (e *DomainError) Wrap(err error) *DomainError {
e.Err = err
return e
}
func NewDomainError(err error, code ErrorCode, details ...any) *DomainError {
func NewErrorFileNotFound(file_id string) *DomainError {
return &DomainError{
Err: err,
Code: code,
Details: details,
Code: ErrCodeFileNotFound,
Message: fmt.Sprintf("File not found: %q", file_id),
}
}
func NewUnexpectedError(err error) *DomainError {
func NewErrorMIMENotSupported(mime string) *DomainError {
return &DomainError{
Err: err,
Code: ErrInternal,
Code: ErrCodeMIMENotSupported,
Message: fmt.Sprintf("MIME not supported: %q", mime),
}
}
func NewErrorTagNotFound(tag_id string) *DomainError {
return &DomainError{
Code: ErrCodeTagNotFound,
Message: fmt.Sprintf("Tag not found: %q", tag_id),
}
}
func NewErrorBadRequest(message string) *DomainError {
return &DomainError{
Code: ErrCodeBadRequest,
Message: message,
}
}
func NewErrorUnexpected() *DomainError {
return &DomainError{
Code: ErrCodeInternal,
Message: "An unexpected error occured",
}
}