Error specification

Detailed example referenceherearrow-up-right

Convention

  • Allexternalexposed errors usegithub.com/asjard/asjard/core/statusprovidedErrorandErrorfmethods

Error code convention

Format: XXX_YYY_ZZZ

Where:

  • XXX: represents the system code, fixed three digits, for example: 100, 101, 102, etc., can be configured viaasjard.service.instance.systemCodeconfiguration

  • YYY: representsHTTP status codearrow-up-right, fixed three digits, for example: 400, 404, 500, etc.

  • ZZZ: represents the error code, variable-length digits, for example: 201, 202, 20001, etc., among them:

    • <=1 ZZZ <= 17are globally shared error codes, usable by any system

    • 18 <= ZZZ <= 200are framework-reserved error codes, business systems should not use them

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