github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/httplib/write_error.go (about)

     1  package httplib
     2  
     3  import (
     4      "net/http"
     5  	"os"
     6  
     7  	"github.com/gin-gonic/gin"
     8  	"github.com/sirupsen/logrus"
     9  
    10  	"github.com/artisanhe/tools/courier/status_error"
    11  )
    12  
    13  var serviceName = ""
    14  
    15  func SetServiceName(name string) {
    16  	serviceName = name
    17  }
    18  
    19  func getServiceName() string {
    20  	if serviceName == "" {
    21  		SetServiceName(os.Getenv("PROJECT_NAME"))
    22  	}
    23  	return serviceName
    24  }
    25  
    26  func errorWithSource(err *status_error.StatusError) *status_error.StatusError {
    27  	return err.WithSource(getServiceName())
    28  }
    29  
    30  func WriteError(c *gin.Context, err error) {
    31  	wrapErrorForEmqx(c, err)
    32  	//statusError := status_error.FromError(err)
    33  	//if statusError.Code == int64(status_error.UnknownError) {
    34  	//	logrus.Warnf("got UnknownError %s", err.Error())
    35  	//}
    36  	//statusError = errorWithSource(statusError)
    37  	//c.Error(statusError)
    38  	//c.JSON(statusError.Status(), statusError)
    39  }
    40  
    41  type EmqxError struct {
    42  	Code    int32  `json:"code"`
    43  	Message string `json:"message"`
    44  	Data struct{} `json:"data"`
    45  }
    46  
    47  func wrapErrorForEmqx(c *gin.Context, err error) {
    48  	statusError := status_error.FromError(err)
    49  	if statusError.Code == int64(status_error.UnknownError) {
    50  		logrus.Warnf("got UnknownError %s", err.Error())
    51  	}
    52  
    53  	errResp := EmqxError{
    54  		Code : int32(statusError.Code),
    55  		Message: statusError.Desc + statusError.Msg + statusError.ErrorFields.String(),
    56  	}
    57  
    58  	c.JSON(http.StatusOK, errResp)
    59  }