Error specification
Convention
Error code convention
Usage example
import (
"github.com/asjard/asjard/core/status"
"github.com/asjard/asjard/pkg/database/mysql"
)
const (
// Custom XXX Not Found error code
CustomeXXXNotFoundErrorCode = 404_201
)
var (
// Custom error, note that it needs to be defined using an anonymous function here
// It contains logic to obtain the systemCode; if defined as a global error there may be an issue of configuration file not being loaded
CustomeXXXError = func() error {return status.Error(CustomeXXXNotFoundErrorCode, "define error as a variable")}
)
func(api XXXAPI) YYY(ctx context, in *pb.Req) (*pb.Resp, error) {
if in.Name == "" {
// This returns a globally shared error code
return nil, status.Error(codes.InvalidArgument, "name is must")
}
db, err := mysql.DB(ctx)
if err != nil {
// This returns a framework-reserved error code
// Same as status.DatabaseNotFoundError
return err
}
var record ExampleTable
if err := db.Where("name=?", in.Name).First(&record).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// This returns the custom error
return nil, status.Errorf(CustomeXXXNotFoundErrorCode, "recode %s not found", in.Name)
}
}
return &pb.Resp{}, nil
}Last updated