feat: manually mirror opencoze's code from bytedance
Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
50
backend/pkg/errorx/internal/msg.go
Normal file
50
backend/pkg/errorx/internal/msg.go
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type withMessage struct {
|
||||
cause error
|
||||
msg string
|
||||
}
|
||||
|
||||
func (w *withMessage) Unwrap() error {
|
||||
return w.cause
|
||||
}
|
||||
|
||||
func (w *withMessage) Error() string {
|
||||
return fmt.Sprintf("%s\ncause=%s", w.msg, w.cause.Error())
|
||||
}
|
||||
|
||||
func wrapf(err error, format string, args ...interface{}) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func Wrapf(err error, format string, args ...interface{}) error {
|
||||
return withStackTraceIfNotExists(wrapf(err, format, args...))
|
||||
}
|
||||
59
backend/pkg/errorx/internal/register.go
Normal file
59
backend/pkg/errorx/internal/register.go
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package internal
|
||||
|
||||
const (
|
||||
DefaultErrorMsg = "Service Internal Error"
|
||||
DefaultIsAffectStability = true
|
||||
)
|
||||
|
||||
var (
|
||||
ServiceInternalErrorCode int32 = 1
|
||||
CodeDefinitions = make(map[int32]*CodeDefinition)
|
||||
)
|
||||
|
||||
type CodeDefinition struct {
|
||||
Code int32
|
||||
Message string
|
||||
IsAffectStability bool
|
||||
}
|
||||
|
||||
type RegisterOption func(definition *CodeDefinition)
|
||||
|
||||
func WithAffectStability(affectStability bool) RegisterOption {
|
||||
return func(definition *CodeDefinition) {
|
||||
definition.IsAffectStability = affectStability
|
||||
}
|
||||
}
|
||||
|
||||
func Register(code int32, msg string, opts ...RegisterOption) {
|
||||
definition := &CodeDefinition{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
IsAffectStability: DefaultIsAffectStability,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(definition)
|
||||
}
|
||||
|
||||
CodeDefinitions[code] = definition
|
||||
}
|
||||
|
||||
func SetDefaultErrorCode(code int32) {
|
||||
ServiceInternalErrorCode = code
|
||||
}
|
||||
86
backend/pkg/errorx/internal/stack.go
Normal file
86
backend/pkg/errorx/internal/stack.go
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type StackTracer interface {
|
||||
StackTrace() string
|
||||
}
|
||||
|
||||
type withStack struct {
|
||||
cause error
|
||||
stack string
|
||||
}
|
||||
|
||||
func (w *withStack) Unwrap() error {
|
||||
return w.cause
|
||||
}
|
||||
|
||||
func (w *withStack) StackTrace() string {
|
||||
return w.stack
|
||||
}
|
||||
|
||||
func (w *withStack) Error() string {
|
||||
return fmt.Sprintf("%s\nstack=%s", w.cause.Error(), w.stack)
|
||||
}
|
||||
|
||||
func stack() string {
|
||||
const depth = 32
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(2, pcs[:])
|
||||
|
||||
b := strings.Builder{}
|
||||
for i := 0; i < n; i++ {
|
||||
fn := runtime.FuncForPC(pcs[i])
|
||||
|
||||
file, line := fn.FileLine(pcs[i])
|
||||
name := trimPathPrefix(fn.Name())
|
||||
b.WriteString(fmt.Sprintf("%s:%d %s\n", file, line, name))
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func trimPathPrefix(s string) string {
|
||||
i := strings.LastIndex(s, "/")
|
||||
s = s[i+1:]
|
||||
i = strings.Index(s, ".")
|
||||
return s[i+1:]
|
||||
}
|
||||
|
||||
func withStackTraceIfNotExists(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// skip if stack has already exist
|
||||
var stackTracer StackTracer
|
||||
if errors.As(err, &stackTracer) {
|
||||
return err
|
||||
}
|
||||
|
||||
return &withStack{
|
||||
err,
|
||||
stack(),
|
||||
}
|
||||
}
|
||||
73
backend/pkg/errorx/internal/stack_test.go
Normal file
73
backend/pkg/errorx/internal/stack_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestWithStack(t *testing.T) {
|
||||
err := withStackTraceIfNotExists(errors.New("test error"))
|
||||
output1 := fmt.Sprintf("%+v", err)
|
||||
assert.Contains(t, output1, "stack_test.go")
|
||||
assert.Contains(t, output1, "withStackTraceIfNotExists")
|
||||
t.Log(output1)
|
||||
}
|
||||
|
||||
func TestPrintStack(t *testing.T) {
|
||||
t.Run("New with stack", func(t *testing.T) {
|
||||
err := NewByCode(1)
|
||||
output1 := fmt.Sprintf("%v", err)
|
||||
assert.Contains(t, output1, "stack_test.go")
|
||||
assert.Contains(t, output1, "TestPrintStack")
|
||||
t.Log(output1)
|
||||
})
|
||||
|
||||
t.Run("New with stack and wrap with fmt.Errorf", func(t *testing.T) {
|
||||
err := NewByCode(1)
|
||||
err1 := fmt.Errorf("err=%w", err)
|
||||
output1 := fmt.Sprintf("%v", err1)
|
||||
assert.Contains(t, output1, "stack_test.go")
|
||||
assert.Contains(t, output1, "TestPrintStack")
|
||||
t.Log(output1)
|
||||
})
|
||||
|
||||
t.Run("wrapf with stack", func(t *testing.T) {
|
||||
err := errors.New("original error")
|
||||
err1 := Wrapf(err, "wrapped error")
|
||||
output1 := fmt.Sprintf("%v", err1)
|
||||
assert.Contains(t, output1, "stack_test.go")
|
||||
assert.Contains(t, output1, "TestPrintStack")
|
||||
t.Log(output1)
|
||||
})
|
||||
|
||||
t.Run("skip wrap with stack if stack has already exist", func(t *testing.T) {
|
||||
err := NewByCode(1)
|
||||
err1 := fmt.Errorf("err1=%w", err)
|
||||
err2 := withStackTraceIfNotExists(err1)
|
||||
_, ok := err2.(StackTracer)
|
||||
assert.False(t, ok)
|
||||
output1 := fmt.Sprintf("%v", err2)
|
||||
assert.Contains(t, output1, "stack_test.go")
|
||||
assert.Contains(t, output1, "TestPrintStack")
|
||||
t.Log(output1)
|
||||
})
|
||||
}
|
||||
195
backend/pkg/errorx/internal/status.go
Normal file
195
backend/pkg/errorx/internal/status.go
Normal file
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
* Copyright 2025 coze-dev Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type StatusError interface {
|
||||
error
|
||||
Code() int32
|
||||
}
|
||||
|
||||
type statusError struct {
|
||||
statusCode int32
|
||||
message string
|
||||
|
||||
ext Extension
|
||||
}
|
||||
|
||||
type withStatus struct {
|
||||
status *statusError
|
||||
|
||||
stack string
|
||||
cause error
|
||||
}
|
||||
|
||||
type Extension struct {
|
||||
IsAffectStability bool
|
||||
Extra map[string]string
|
||||
}
|
||||
|
||||
func (w *statusError) Code() int32 {
|
||||
return w.statusCode
|
||||
}
|
||||
|
||||
func (w *statusError) IsAffectStability() bool {
|
||||
return w.ext.IsAffectStability
|
||||
}
|
||||
|
||||
func (w *statusError) Msg() string {
|
||||
return w.message
|
||||
}
|
||||
|
||||
func (w *statusError) Error() string {
|
||||
return fmt.Sprintf("code=%d message=%s", w.statusCode, w.message)
|
||||
}
|
||||
|
||||
func (w *statusError) Extra() map[string]string {
|
||||
return w.ext.Extra
|
||||
}
|
||||
|
||||
// Unwrap supports go errors.Unwrap().
|
||||
func (w *withStatus) Unwrap() error {
|
||||
return w.cause
|
||||
}
|
||||
|
||||
// Is supports go errors.Is().
|
||||
func (w *withStatus) Is(target error) bool {
|
||||
var ws StatusError
|
||||
if errors.As(target, &ws) && w.status.Code() == ws.Code() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// As supports go errors.As().
|
||||
func (w *withStatus) As(target interface{}) bool {
|
||||
if errors.As(w.status, target) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (w *withStatus) StackTrace() string {
|
||||
return w.stack
|
||||
}
|
||||
|
||||
func (w *withStatus) Error() string {
|
||||
b := strings.Builder{}
|
||||
b.WriteString(w.status.Error())
|
||||
|
||||
if w.cause != nil {
|
||||
b.WriteString("\n")
|
||||
b.WriteString(fmt.Sprintf("cause=%s", w.cause))
|
||||
}
|
||||
|
||||
if w.stack != "" {
|
||||
b.WriteString("\n")
|
||||
b.WriteString(fmt.Sprintf("stack=%s", w.stack))
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type Option func(ws *withStatus)
|
||||
|
||||
func Param(k, v string) Option {
|
||||
return func(ws *withStatus) {
|
||||
if ws == nil || ws.status == nil {
|
||||
return
|
||||
}
|
||||
ws.status.message = strings.Replace(ws.status.message, fmt.Sprintf("{%s}", k), v, -1)
|
||||
}
|
||||
}
|
||||
|
||||
func Extra(k, v string) Option {
|
||||
return func(ws *withStatus) {
|
||||
if ws == nil || ws.status == nil {
|
||||
return
|
||||
}
|
||||
if ws.status.ext.Extra == nil {
|
||||
ws.status.ext.Extra = make(map[string]string)
|
||||
}
|
||||
ws.status.ext.Extra[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
func NewByCode(code int32, options ...Option) error {
|
||||
ws := &withStatus{
|
||||
status: getStatusByCode(code),
|
||||
cause: nil,
|
||||
stack: stack(),
|
||||
}
|
||||
|
||||
for _, opt := range options {
|
||||
opt(ws)
|
||||
}
|
||||
|
||||
return ws
|
||||
}
|
||||
|
||||
func WrapByCode(err error, code int32, options ...Option) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ws := &withStatus{
|
||||
status: getStatusByCode(code),
|
||||
cause: err,
|
||||
}
|
||||
|
||||
for _, opt := range options {
|
||||
opt(ws)
|
||||
}
|
||||
|
||||
// skip if stack has already exist
|
||||
var stackTracer StackTracer
|
||||
if errors.As(err, &stackTracer) {
|
||||
return ws
|
||||
}
|
||||
|
||||
ws.stack = stack()
|
||||
|
||||
return ws
|
||||
}
|
||||
|
||||
func getStatusByCode(code int32) *statusError {
|
||||
codeDefinition, ok := CodeDefinitions[code]
|
||||
if ok {
|
||||
// predefined err code
|
||||
return &statusError{
|
||||
statusCode: code,
|
||||
message: codeDefinition.Message,
|
||||
ext: Extension{
|
||||
IsAffectStability: codeDefinition.IsAffectStability,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return &statusError{
|
||||
statusCode: code,
|
||||
message: DefaultErrorMsg,
|
||||
ext: Extension{
|
||||
IsAffectStability: DefaultIsAffectStability,
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user