github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/http/model/bizerror.go (about)

     1  package model
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  // BizError is used for business error implemented error interface
     8  // StatusCode will be set to http response status code
     9  // ErrCode is used for business error code
    10  // ErrMsg is custom error message
    11  type BizError struct {
    12  	StatusCode int
    13  	ErrCode    int
    14  	ErrMsg     string
    15  	Cause      error
    16  }
    17  
    18  type BizErrorOption func(bizError *BizError)
    19  
    20  func WithStatusCode(statusCode int) BizErrorOption {
    21  	return func(bizError *BizError) {
    22  		bizError.StatusCode = statusCode
    23  	}
    24  }
    25  
    26  func WithErrCode(errCode int) BizErrorOption {
    27  	return func(bizError *BizError) {
    28  		bizError.ErrCode = errCode
    29  	}
    30  }
    31  
    32  func WithCause(cause error) BizErrorOption {
    33  	return func(bizError *BizError) {
    34  		bizError.Cause = cause
    35  	}
    36  }
    37  
    38  // NewBizError is factory function for creating an instance of BizError struct
    39  func NewBizError(err error, opts ...BizErrorOption) BizError {
    40  	bz := BizError{
    41  		StatusCode: 500,
    42  		ErrMsg:     err.Error(),
    43  	}
    44  	for _, fn := range opts {
    45  		fn(&bz)
    46  	}
    47  	return bz
    48  }
    49  
    50  // String function is used for printing string representation of a BizError instance
    51  func (b BizError) String() string {
    52  	if b.ErrCode > 0 {
    53  		return fmt.Sprintf("%d %s", b.ErrCode, b.ErrMsg)
    54  	}
    55  	return b.ErrMsg
    56  }
    57  
    58  // Error is used for implementing error interface
    59  func (b BizError) Error() string {
    60  	return b.String()
    61  }