github.com/yukk001/go1.10.8@v0.0.0-20190813125351-6df2d3982e20/doc/progs/error.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This file contains the code snippets included in "Error Handling and Go." 6 7 package main 8 9 import ( 10 "encoding/json" 11 "errors" 12 "fmt" 13 "log" 14 "net" 15 "os" 16 "time" 17 ) 18 19 type File struct{} 20 21 func Open(name string) (file *File, err error) { 22 // OMIT 23 panic(1) 24 // STOP OMIT 25 } 26 27 func openFile() { // OMIT 28 f, err := os.Open("filename.ext") 29 if err != nil { 30 log.Fatal(err) 31 } 32 // do something with the open *File f 33 // STOP OMIT 34 _ = f 35 } 36 37 // errorString is a trivial implementation of error. 38 type errorString struct { 39 s string 40 } 41 42 func (e *errorString) Error() string { 43 return e.s 44 } 45 46 // STOP OMIT 47 48 // New returns an error that formats as the given text. 49 func New(text string) error { 50 return &errorString{text} 51 } 52 53 // STOP OMIT 54 55 func Sqrt(f float64) (float64, error) { 56 if f < 0 { 57 return 0, errors.New("math: square root of negative number") 58 } 59 // implementation 60 return 0, nil // OMIT 61 } 62 63 // STOP OMIT 64 65 func printErr() (int, error) { // OMIT 66 f, err := Sqrt(-1) 67 if err != nil { 68 fmt.Println(err) 69 } 70 // STOP OMIT 71 // fmtError OMIT 72 if f < 0 { 73 return 0, fmt.Errorf("math: square root of negative number %g", f) 74 } 75 // STOP OMIT 76 return 0, nil 77 } 78 79 type NegativeSqrtError float64 80 81 func (f NegativeSqrtError) Error() string { 82 return fmt.Sprintf("math: square root of negative number %g", float64(f)) 83 } 84 85 // STOP OMIT 86 87 type SyntaxError struct { 88 msg string // description of error 89 Offset int64 // error occurred after reading Offset bytes 90 } 91 92 func (e *SyntaxError) Error() string { return e.msg } 93 94 // STOP OMIT 95 96 func decodeError(dec *json.Decoder, val struct{}) error { // OMIT 97 var f os.FileInfo // OMIT 98 if err := dec.Decode(&val); err != nil { 99 if serr, ok := err.(*json.SyntaxError); ok { 100 line, col := findLine(f, serr.Offset) 101 return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err) 102 } 103 return err 104 } 105 // STOP OMIT 106 return nil 107 } 108 109 func findLine(os.FileInfo, int64) (int, int) { 110 // place holder; no need to run 111 return 0, 0 112 } 113 114 func netError(err error) { // OMIT 115 for { // OMIT 116 if nerr, ok := err.(net.Error); ok && nerr.Temporary() { 117 time.Sleep(1e9) 118 continue 119 } 120 if err != nil { 121 log.Fatal(err) 122 } 123 // STOP OMIT 124 } 125 } 126 127 func main() {}