Created
June 5, 2020 11:56
-
-
Save rogerwelin/f31ab3cb09b0f716d5e780f32a9002a6 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 ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/pkg/errors" | |
) | |
var ErrNotFound = errors.New("Page not found") | |
var ErrBadRequest = errors.New("Bad Request") | |
func handleError(resp *http.Response) error { | |
switch resp.StatusCode { | |
case 400: | |
return ErrBadRequest | |
case 404: | |
return ErrNotFound | |
} | |
return nil | |
} | |
func getRequest() (int, error) { | |
resp, err := http.Get("http://www.google.com/blabla") | |
if err != nil { | |
return 0, err | |
} | |
defer resp.Body.Close() | |
err = handleError(resp) | |
if err != nil { | |
return 0, err | |
} | |
return resp.StatusCode, nil | |
} | |
func main() { | |
code, err := getRequest() | |
switch errors.Cause(err) { | |
case ErrNotFound: | |
fmt.Println("its not there") | |
case ErrBadRequest: | |
fmt.Println("oh no") | |
default: | |
// unknown error | |
log.Fatalf("this was unexpected: %v\n", err) | |
} | |
fmt.Println(code) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment