package main
import ( "fmt" "io" "os")
// wrapErr is an error wrapping functionfunc wrapErr(err error, format string, args ...interface{}) error { return fmt.Errorf( "%s: %s", fmt.Sprintf(format, args...), err.Error(), ) // or other error implementation}
// like the proposed try function but with custom wrappervar try = makeTry(wrapErr)
// use like the proposed try with extra wrapping argumentsfunc CopyFile(src, dest string) (err error) { r := try(os.Open(src), "open %s", src) // if there is an error, it will be "open <src>: <err>" as returned by wrapErr defer r.Close() w := try(os.Create(dest), "create %s", dest) defer func() { w.Close() if err != nil { os.Remove(dest) } }() try(io.Copy(w, r)) // bare try without arguments, so no wrapping try(w.Close()) return nil}
Are you serious?
package main
import ( "fmt" "io" "os")
type Err struct { Code string Message string Cause error}
var _ error = Err{}
func (e Err) Error() string { return fmt.Sprintf("[%s] %s: %s", e.Code, e.Message, e.Cause.Error())}
// wrapErr annotates an error with code and messagefunc wrapErr(err error, code string, message string, args ...interface{}) error { return Err{ Code: code, Message: fmt.Sprintf(message, args...), Cause: err,
}}
// like the proposed try function but with custom wrappervar try = makeTry(wrapErr)
// use like the proposed try with extra wrapping argumentsfunc CopyFile(src, dest string) (err error) {
r := try(os.Open(src), "Open", "open %s", src) defer r.Close() w := try(os.Create(dest), "Create", "create %s", dest)