|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "strconv" |
| 8 | +) |
| 9 | + |
| 10 | +func main() { |
| 11 | + // in go, there are no exceptions |
| 12 | + // in go, error handled using return values |
| 13 | + |
| 14 | + // try to use strconv package from go |
| 15 | + // we are going to convert x into integer |
| 16 | + x := "name" |
| 17 | + n, err := strconv.Atoi(x) |
| 18 | + if err != nil { |
| 19 | + log.Printf("x cannot be converted to an integer. err: %s\n", err.Error()) |
| 20 | + } else { |
| 21 | + log.Printf("n: %d is integer value of x\n", n) |
| 22 | + } |
| 23 | + |
| 24 | + // err is an interface value from "error" interface |
| 25 | + // and because its an interface, we can define our own error |
| 26 | + |
| 27 | + // using package errors to define error |
| 28 | + err = check(x) |
| 29 | + if err != nil { |
| 30 | + log.Printf("got err: %s\n", err.Error()) |
| 31 | + } |
| 32 | + |
| 33 | + // using defined variables, it is very usefull |
| 34 | + // like catching exception on other language |
| 35 | + err = anotherCheck(x) |
| 36 | + if err == ErrInvalidLength { |
| 37 | + log.Println("X is less than 5 char") |
| 38 | + } |
| 39 | + |
| 40 | + // using type struct, which we can got more information about the error |
| 41 | + // we can do type assertion here |
| 42 | + err = checkString(x) |
| 43 | + terr, ok := err.(MyError) |
| 44 | + if ok { |
| 45 | + log.Println(terr.Error()) |
| 46 | + log.Printf("%d: %s\n", terr.Code, terr.Message) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func check(x string) error { |
| 51 | + if len(x) < 5 { |
| 52 | + return errors.New("Invalid Length") |
| 53 | + } |
| 54 | + return nil |
| 55 | +} |
| 56 | + |
| 57 | +var ErrInvalidLength = errors.New("Invalid Length") |
| 58 | + |
| 59 | +func anotherCheck(x string) error { |
| 60 | + if len(x) < 5 { |
| 61 | + return ErrInvalidLength |
| 62 | + } |
| 63 | + return nil |
| 64 | +} |
| 65 | + |
| 66 | +type MyError struct { |
| 67 | + Code int |
| 68 | + Message string |
| 69 | +} |
| 70 | + |
| 71 | +func (e MyError) Error() string { |
| 72 | + return fmt.Sprintf("%d: %s", e.Code, e.Message) |
| 73 | +} |
| 74 | + |
| 75 | +func checkString(x string) error { |
| 76 | + if len(x) < 5 { |
| 77 | + return MyError{Code: 409, Message: "Invalid Length"} |
| 78 | + } |
| 79 | + return nil |
| 80 | +} |
0 commit comments