Skip to content

Commit

Permalink
Upgrade error module
Browse files Browse the repository at this point in the history
  • Loading branch information
naeemaei committed Oct 7, 2023
1 parent 06c67e4 commit 5af3748
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 13-Errors/02-Error/17162-7Learn/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
3 changes: 3 additions & 0 deletions 13-Errors/02-Error/17162-7Learn/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module ErrorExample

go 1.20
54 changes: 54 additions & 0 deletions 13-Errors/02-Error/17162-7Learn/main.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 5af3748

Please sign in to comment.