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