55 lines
1.8 KiB
Go
55 lines
1.8 KiB
Go
package exerr
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
)
|
|
|
|
type ErrorCategory struct{ Category string }
|
|
|
|
var (
|
|
CatWrap = ErrorCategory{"Wrap"} // The error is simply wrapping another error (e.g. when a grpc call returns an error)
|
|
CatSystem = ErrorCategory{"System"} // An internal system error (e.g. connection to db failed)
|
|
CatUser = ErrorCategory{"User"} // The user (the API caller) did something wrong (e.g. he has no permissions to do this)
|
|
CatForeign = ErrorCategory{"Foreign"} // A foreign error that some component threw (e.g. an unknown mongodb error), happens if we call Wrap(..) on an non-bmerror value
|
|
)
|
|
|
|
func (e *ErrorCategory) UnmarshalJSON(bytes []byte) error {
|
|
return json.Unmarshal(bytes, &e.Category)
|
|
}
|
|
|
|
func (e ErrorCategory) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(e.Category)
|
|
}
|
|
|
|
func (e *ErrorCategory) UnmarshalBSONValue(bt byte, data []byte) error {
|
|
if bson.Type(bt) == bson.TypeNull {
|
|
// we can't set nil in UnmarshalBSONValue (so we use default(struct))
|
|
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
|
|
// https://stackoverflow.com/questions/75167597
|
|
// https://jira.mongodb.org/browse/GODRIVER-2252
|
|
*e = ErrorCategory{}
|
|
return nil
|
|
}
|
|
if bson.Type(bt) != bson.TypeString {
|
|
return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bson.Type(bt)))
|
|
}
|
|
var tt string
|
|
err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
*e = ErrorCategory{tt}
|
|
return nil
|
|
}
|
|
|
|
func (e ErrorCategory) MarshalBSONValue() (byte, []byte, error) {
|
|
tp, data, err := bson.MarshalValue(e.Category)
|
|
return byte(tp), data, err
|
|
}
|
|
|
|
//goland:noinspection GoUnusedGlobalVariable
|
|
var AllCategories = []ErrorCategory{CatWrap, CatSystem, CatUser, CatForeign}
|