Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove duplicate error code check and add some public method #22

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions terror_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import (
"runtime"
"strconv"
"strings"

"github.com/pingcap/log"
"github.com/pkg/errors"
"go.uber.org/zap"
)

// Error is the 'prototype' of a type of errors.
Expand Down Expand Up @@ -128,10 +132,10 @@ func (e *Error) Error() string {
if len(describe) == 0 {
describe = ErrCodeText(strconv.Itoa(int(e.code)))
}
return fmt.Sprintf("[%s] %s", e.RFCCode(), e.getMsg())
return fmt.Sprintf("[%s] %s", e.RFCCode(), e.GetMsg())
}

func (e *Error) getMsg() string {
func (e *Error) GetMsg() string {
if len(e.args) > 0 {
return fmt.Sprintf(e.message, e.args...)
}
Expand Down Expand Up @@ -251,7 +255,7 @@ type jsonError struct {
// This function is reserved for compatibility.
func (e *Error) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonError{
Error: e.getMsg(),
Error: e.GetMsg(),
Description: e.Description,
Workaround: e.Workaround,
RFCCode: e.RFCCode(),
Expand Down Expand Up @@ -291,3 +295,29 @@ func (e *Error) UnmarshalJSON(data []byte) error {
}
return nil
}

// MustNil cleans up and fatals if err is not nil.
func MustNil(err error, closeFuns ...func()) {
if err != nil {
for _, f := range closeFuns {
f()
}
log.Fatal("unexpected error", zap.Error(err))
}
}

// Call executes a function and checks the returned err.
func Call(fn func() error) {
err := fn()
if err != nil {
log.Error("function call errored", zap.Error(err))
}
}

// Log logs the error if it is not nil.
func Log(err error) {
if err != nil {
log.Error("encountered error", zap.Error(errors.WithStack(err)))
}
}

3 changes: 0 additions & 3 deletions terror_registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,6 @@ func (ec *ErrClass) DefineError() *Builder {
// RegisterError try to register an error to a class.
// return true if success.
func (ec *ErrClass) RegisterError(err *Error) bool {
if _, ok := ec.errors[err.ID()]; ok {
return false
}
err.class = ec
ec.errors[err.ID()] = err
return true
Expand Down