Git Product home page Git Product logo

Comments (3)

at15 avatar at15 commented on July 20, 2024

this https://blog.golang.org/errors-are-values shows how to avoid multiple if err != nil check, which appears a lot in the Ping method for tsdb clients

// Ping use KairosDB version API to check if it alive
func (client *KairosDBHTTPClient) Ping() error {
	res, err := http.Get(client.Config.Host.HostURL() + "/api/v1/version")
	if err != nil {
		log.Warn("can't get kairosdb version")
		log.Debug(err.Error())
		return err
	}
	defer res.Body.Close()
	resContent, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Warn("can't read response body")
		log.Debug(err.Error())
		return err
	}
	var resData map[string]string
	if err := json.Unmarshal(resContent, &resData); err != nil {
		log.Warn("can't parse json")
		log.Debug(err.Error())
		return err
	}
	log.Info("KairosDB version is " + resData["version"])
	return nil
}

And his example is

_, err = fd.Write(p0[a:b])
if err != nil {
    return err
}
_, err = fd.Write(p1[c:d])
if err != nil {
    return err
}
_, err = fd.Write(p2[e:f])
if err != nil {
    return err
}
// and so on

his ultimate solution is

type errWriter struct {
    w   io.Writer
    err error
}
func (ew *errWriter) write(buf []byte) {
    if ew.err != nil {
        return
    }
    _, ew.err = ew.w.Write(buf)
}
ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
    return ew.err
}

from xephon-b.

at15 avatar at15 commented on July 20, 2024

https://justinas.org/best-practices-for-errors-in-go/

  • When the user explicitly asks: Okay
    • i.e. regexp.MustCompile
  • When setting up: Maybe
    • i.e. http server can't bind to port
    • i.e. unable to connect to database server

Given a small set of errors, the best way to handle this is to predefine each error publicly at the package level.

  • TODO: what about error that have some custom messages? solved in the following paragraph
var ErrNoSpaceLeft = errors.New("no space left on the device")
var ErrPermissionDenied = errors.New("permission denied")

func doStuff() error {
    if someCondition {
        return ErrNoSpaceLeft
    } else {
        return ErrPermissionDenied 
    }
}

A custom error type is the best solution to this problem. Go's implicit interfaces make creating one easy: to conform to the error interface, we only need to have an Error() method that returns a string.

type HTTPError struct {
    Code        int
    Description string
}

func (h HTTPError) Error() string {
    return fmt.Sprintf("HTTP %d: %s", h.Code, h.Description)
}

for stack trace, it suggests https://github.com/juju/errgo which is not updated after 2014, so I think pkg/errors is better.

and return error interface and let user do type conversion

Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

from xephon-b.

at15 avatar at15 commented on July 20, 2024

https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully

the first two part is ok, but from the Opaque errors, I have some disagreement

  • opaque error is just like returning true or false
  • assert error behavior use interface, how can it not import package in order to test methods TODO: I might be wrong

and the following I do agree

  • use errors.Wrap
  • use errors.Cause to track cause

from xephon-b.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.