github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/pkg/utils/syserror.go (about) 1 /* 2 * Copyright (c) 2020-present unTill Pro, Ltd. 3 */ 4 5 package coreutils 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "net/http" 12 13 "github.com/voedger/voedger/pkg/appdef" 14 ) 15 16 type SysError struct { 17 HTTPStatus int 18 QName appdef.QName 19 Message string 20 Data string 21 } 22 23 func NewSysError(statusCode int) error { 24 return SysError{HTTPStatus: statusCode} 25 } 26 27 func WrapSysError(err error, defaultStatusCode int) error { 28 if err == nil { 29 return nil 30 } 31 var res SysError 32 if !errors.As(err, &res) { 33 res = SysError{Message: err.Error(), HTTPStatus: defaultStatusCode} 34 } 35 return res 36 } 37 38 func (he SysError) Error() string { 39 if len(he.Message) == 0 && he.HTTPStatus > 0 { 40 return fmt.Sprintf("%d %s", he.HTTPStatus, http.StatusText(he.HTTPStatus)) 41 } 42 return he.Message 43 } 44 45 func (he SysError) ToJSON() string { 46 b := bytes.NewBuffer(nil) 47 b.WriteString(fmt.Sprintf(`{"sys.Error":{"HTTPStatus":%d,"Message":%q`, he.HTTPStatus, he.Message)) 48 if he.QName != appdef.NullQName { 49 b.WriteString(fmt.Sprintf(`,"QName":"%s"`, he.QName.String())) 50 } 51 if len(he.Data) > 0 { 52 b.WriteString(fmt.Sprintf(`,"Data":%q`, he.Data)) 53 } 54 b.WriteString("}}") 55 return b.String() 56 }