Created
March 6, 2020 15:47
-
-
Save luizvnasc/67306865aee95dadfc00e53d0d742481 to your computer and use it in GitHub Desktop.
Exemplo de error handling com go 1.13
This file contains hidden or 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 DBError struct { | |
message string | |
err error | |
} | |
func (dbErr *DBError) Error() string { | |
return dbErr.message | |
} | |
func (dbErr *DBError) Wrap(e error) { | |
dbErr.err = e | |
} | |
func (dbErr *DBError) Unwrap() error { | |
return dbErr.err | |
} | |
type OtherError string | |
func (oErr OtherError) Error() string { | |
return string(oErr) | |
} | |
const ( | |
ErrPermissionDenied = OtherError("permission denied") | |
ErrNotFound = OtherError("not found") | |
) | |
func DoSomething1() *DBError { | |
err := &DBError{message: "error doing something"} | |
err.Wrap(ErrPermissionDenied) | |
return err | |
} | |
func DoSomething2() *DBError { | |
err := &DBError{message: "error doing something"} | |
err.Wrap(ErrNotFound) | |
return err | |
} | |
func main() { | |
err := DoSomething1() | |
if errors.Is(err, ErrPermissionDenied) { | |
fmt.Println("permission error") | |
} | |
err = DoSomething2() | |
if errors.Is(err, ErrNotFound) { | |
fmt.Println("not found error") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment