2

I wrote this very basic parser that goes through Reddit JSON and am curious how I can specifically manage an error in Go.

For example I have this "Get" method for a link:

func Get(reddit string) ([]Item, error) { url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit) resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, err } /* * Other code here */ } 

How can I handle, say, a 404 error from the StatusCode? I know I can test for the 404 error itself:

if resp.StatusCode == http.StatusNotfound { //do stuff here } 

But is there a way I can directly manage the resp.StatusCode != http.StatusOK without having to write a bunch of if statements? Is there a way I can use err in a switch statement?

2 Answers 2

1

Firstly note that http.Get doesn't return an error for an HTTP return which isn't 200. The Get did its job successfully even when the server gave it a 404 error. From the docs

A non-2xx response doesn't cause an error.

Therfore in your code, err will be nil when you call this which means it will return err=nil which probably isn't what you want.

if resp.StatusCode != http.StatusOK { return nil, err } 

This should do what you want

if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("HTTP Error %d: %s", resp.StatusCode, resp.Status) } 

Which will return an error for any kind of HTTP error, with a message as to what it was.

Sign up to request clarification or add additional context in comments.

Comments

0

Sure you can:

package main import "fmt" func main() { var err error switch err { case nil: fmt.Println("Is nil") } } 

https://play.golang.org/p/4VdHW87wCr

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.