28
loading...
This website collects cookies to deliver better user experience
if err := function(); err != nil {
// something happens
return err
}
errors
package to handle identifying and working errors in a better way, specifically:==
operator we can use something like:if err == io.ErrUnexpectedEOF // Before
if errors.Is(err, io.ErrUnexpectedEOF) // After
if e, ok := err.(*os.PathError); ok // Before
var e *os.PathError // After
if errors.As(err, &e)
fmt
verb %w
and errors.Unwrap, with the idea of decorating errors with more details but still keeping the original error intact. For example:
fmt.Errorf("something failed: %w", err)
errors.Unwrap
function is going to make more sense when looking at the code implemented below.The code used for this post is available on Github.
// Error represents an error that could be wrapping another error, it includes a code for determining
// what triggered the error.
type Error struct {
orig error
msg string
code ErrorCode
}
const (
ErrorCodeUnknown ErrorCode = iota
ErrorCodeNotFound
ErrorCodeInvalidArgument
)
WrapErrorf
to wrap the error and add extra details regarding what happend:return internal.Task{}, internal.WrapErrorf(err, internal.ErrorCodeUnknown, "insert task")
func renderErrorResponse(w http.ResponseWriter, msg string, err error) {
resp := ErrorResponse{Error: msg}
status := http.StatusInternalServerError
var ierr *internal.Error
if !errors.As(err, &ierr) {
resp.Error = "internal error"
} else {
switch ierr.Code() {
case internal.ErrorCodeNotFound:
status = http.StatusNotFound
case internal.ErrorCodeInvalidArgument:
status = http.StatusBadRequest
}
}
renderResponse(w, resp, status)
}