Created
July 30, 2020 12:41
-
-
Save maxwellgithinji/9d6612b92f9d3c2544e1af8afdd2a6a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
type ErrFile struct { | |
Filename string | |
Base error | |
} | |
func (e ErrFile) Error() string { | |
return fmt.Sprintf("File %s: %v", e.Filename, e.Base) | |
} | |
func (e ErrFile) Unwrap() error { | |
return e.Base | |
} | |
var ErrNotExist = fmt.Errorf("File does not exist") | |
func openFile(filename string) (string, error) { | |
return "", ErrNotExist | |
} | |
func openFile2(filename string) (string, error) { | |
return "", ErrFile{ | |
Filename: filename, | |
Base: ErrNotExist, | |
} | |
} | |
func main() { | |
_, err := openFile("test.txt") | |
if err != nil { | |
//THe easiest way is using errorf and %w | |
wrappedErr := fmt.Errorf("Unable to open file %v: %w", "test.txt", err) | |
if errors.Is(wrappedErr, ErrNotExist) { | |
fmt.Println("This is an ErrNotExist") | |
} | |
fmt.Println(wrappedErr) | |
} | |
_, err = openFile2("test.txt") | |
if err != nil { | |
if errors.Is(err, ErrNotExist) { | |
fmt.Println("This is an ErrNotExist") | |
} | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment