diff --git a/13-Errors/02-Error/17162-7Learn/.vscode/launch.json b/13-Errors/02-Error/17162-7Learn/.vscode/launch.json new file mode 100644 index 0000000..f79d986 --- /dev/null +++ b/13-Errors/02-Error/17162-7Learn/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/main.go" + } + ] +} \ No newline at end of file diff --git a/13-Errors/02-Error/17162-7Learn/go.mod b/13-Errors/02-Error/17162-7Learn/go.mod new file mode 100644 index 0000000..fb632d2 --- /dev/null +++ b/13-Errors/02-Error/17162-7Learn/go.mod @@ -0,0 +1,3 @@ +module ErrorExample + +go 1.20 diff --git a/13-Errors/02-Error/17162-7Learn/main.go b/13-Errors/02-Error/17162-7Learn/main.go new file mode 100644 index 0000000..257fd29 --- /dev/null +++ b/13-Errors/02-Error/17162-7Learn/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "errors" + "fmt" + "io" + "os" +) + +type IOError struct { + FileName string + Message string + Err error +} + +func (error *IOError) Unwrap() error { + return error.Err +} + +func (error IOError) Error() string { + return fmt.Sprintf("IO error occurred: FileName: %s Message: %s Detail: %s", error.FileName, error.Message, error.Err.Error()) +} + +func CopyFile(srcName, dstName string) error { + src, err := os.Open(srcName) + if err != nil { + return &IOError{FileName: srcName, Message: "during copy file could not open source file", Err: err} + } + //defer src.Close() + dst, err := os.Create(dstName) + if err != nil { + return &IOError{FileName: srcName, Message: "during copy file could not create destination file", Err: err} + } + dst.Close() + _, err = io.Copy(dst, src) + fmt.Printf("io error: %s\n", err) + var ioErr IOError = IOError{} + if errors.Is(err,ioErr){ + fmt.Printf("cast error: %s\n", ioErr) + } + if err != nil { + return &IOError{FileName: srcName, Message: "during copy file could not copy", Err: err} + } + return nil +} +func main() { + err := CopyFile("src.txt", "dst.txt") + fmt.Printf("%s\n", err) + fmt.Printf("Unwrap Error: %s", errors.Unwrap(err)) + + if err != nil { + fmt.Printf("Error: %s\n", err) + } +}