Handling Errors - adampresley/swapi-go GitHub Wiki

There are two type of errors that can occur when communicating with the SWAPI RESTful interface. The first type of error is one returned from the API. This is most likely going to come in the form of a 404 to indicate a requested resource could not be found. The second type of error is a hard error communicating with the service, or un-marshalling the JSON data to the appropriate structure. This is less likely to happen, but should be checked just the same.

Resource Not Found - 404

Each method in the SWAPI Go wrapper will return the HTTP status that is returned from the SWAPI RESTful interface. For example let's say that you are asking for the planet with an ID of 2, and it does not exist. The SWAPI service will return a 404 with a JSON structure containing a detail message. Here is an example of handling this.

	planetId := 2

	client := swapi.NewClient()
	planet, status, _ := client.GetPlanetById(planetId)

	if status == 404 {
		log.Println("The requested planet with an ID of", planetId, "could not be found")
	}

Hard Stop Error

In the event that there is an issue communicating with the SWAPI RESTful service server, or even un-marshalling JSON data, the 3rd return variable will contain an error structure. Handling that could look something like this.

	planetId := 2

	client := swapi.NewClient()
	planet, status, err := client.GetPlanetById(planetId)

	if err != nil {
		log.Fatalf("There was a hard error attempting to retrieve the planet with an ID of %d: %s", planetId, err.Error())
	}
⚠️ **GitHub.com Fallback** ⚠️