More terse error handling in Go

前端 未结 2 2008
-上瘾入骨i
-上瘾入骨i 2021-01-14 19:53

How do I handle a lot of errors in Go?

I look at my code and find that it is full of error handlers:

err = result.Scan(&bot.BID, &bot.LANGUAG         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 20:35

    If the error is "real", you should (have to) handle it if you don't want unexpected panics at runtime.

    To supplement VonC's answer about the errWriter technique, there are more cases where you can reduce error handling code:

    These are the cases when you know that even though a function or method may return an error, it will not (e.g. you're supplying the parameters from source code which you know will work). In these cases you (or the author of the library) can provide helper functions (or methods) which do not return the error but raise a runtime panic if it still occurs.

    Great examples of these are the template and regexp packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason the template package provides the Must(t *Template, err error) *Template function and the regexp package provides the MustCompile(str string) *Regexp function: they don't return errors because their intended use is where the input is guaranteed to be valid.

    Examples:

    // "text" is a valid template, parsing it will not fail
    var t = template.Must(template.New("name").Parse("text"))
    
    // `^[a-z]+\[[0-9]+\]$` is a valid regexp, always compiles
    var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
    

提交回复
热议问题