-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_errors.go
More file actions
87 lines (74 loc) · 1.93 KB
/
Copy pathexample_errors.go
File metadata and controls
87 lines (74 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"errors"
"fmt"
"log"
"os"
)
// Example 1: Basic Error Handling
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("Cannot divide by zero.")
}
return a / b, nil
}
// Example 2: Panic and Recover
func riskyOperation() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
fmt.Println("Starting risky operation.")
panic("Something went wrong!")
fmt.Println("This line will never be executed.")
}
// Example 3: Custom Errors
type CustomError struct {
Function string
Message string
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Error in %s: %s", e.Function, e.Message)
}
func testFunction() error {
return &CustomError{Function: "testFunction", Message: "Something bad happened"}
}
// Example 4: Logging Errors
func logError(err error) {
file, fileErr := os.OpenFile("error.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if fileErr != nil {
log.Fatalf("Failed to open error log file: %v", fileErr)
}
defer file.Close()
// Print error to the file
_, writeErr := fmt.Fprintf(file, "ERROR: %v\n", err)
if writeErr != nil {
fmt.Printf("Failed to write to error log file: %v\n", writeErr)
}
}
func main() {
// Example 1: Basic Error Handling
fmt.Println("Example 1: Basic Error Handling")
result, err := divide(4, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
// Example 2: Panic and Recover
fmt.Println("\nExample 2: Panic and Recover")
riskyOperation()
fmt.Println("Continuing execution after risky operation.")
// Example 3: Custom Errors
fmt.Println("\nExample 3: Custom Errors")
err = testFunction()
if err != nil {
fmt.Println(err)
}
// Example 4: Logging Errors
fmt.Println("\nExample 4: Logging Errors")
err = errors.New("This is a test error")
logError(err)
fmt.Println("Open the 'files' at the top left and see the error logged to `error.log`.")
}