Here's another demo that annotate errors with custom type.

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 message
func 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 wrapper
var try = makeTry(wrapErr)

// use like the proposed try with extra wrapping arguments
func 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)
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
}



-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/cdea780e-0768-42aa-a71c-a8cfe250d7cf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to