refactor error handling in findRecord

This commit is contained in:
clint shryock 2016-01-29 11:56:19 -06:00
parent 125987994c
commit 3bbb21d115
1 changed files with 30 additions and 5 deletions

View File

@ -2,6 +2,7 @@ package aws
import (
"bytes"
"errors"
"fmt"
"log"
"strings"
@ -16,6 +17,9 @@ import (
"github.com/aws/aws-sdk-go/service/route53"
)
var r53NoRecordsFound = errors.New("No matching Hosted Zone found")
var r53NoHostedZoneFound = errors.New("No matching records found")
func resourceAwsRoute53Record() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRoute53RecordCreate,
@ -244,9 +248,14 @@ func resourceAwsRoute53RecordCreate(d *schema.ResourceData, meta interface{}) er
func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) error {
record, err := findRecord(d, meta)
if err != nil {
log.Printf("[DEBUG] No matching record found for: %s, removing from state file", d.Id())
switch err {
case r53NoHostedZoneFound, r53NoRecordsFound:
log.Printf("[DEBUG] %s for: %s, removing from state file", err, d.Id())
d.SetId("")
return nil
default:
return err
}
}
err = d.Set("records", flattenResourceRecords(record.ResourceRecords))
@ -268,6 +277,21 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro
return nil
}
// findRecord takes a ResourceData struct for aws_resource_route53_record. It
// uses the referenced zone_id to query Route53 and find information on it's
// records.
//
// If records are found, it returns the matching
// route53.ResourceRecordSet and nil for the error.
//
// If no hosted zone is found, it returns a nil recordset and r53NoHostedZoneFound
// error.
//
// If no matching recordset is found, it returns nil and a r53NoRecordsFound
// error
//
// If there are other errors, it returns nil a nil recordset and passes on the
// error.
func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceRecordSet, error) {
conn := meta.(*AWSClient).r53conn
// Scan for a
@ -277,7 +301,7 @@ func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceReco
zoneRecord, err := conn.GetHostedZone(&route53.GetHostedZoneInput{Id: aws.String(zone)})
if err != nil {
if r53err, ok := err.(awserr.Error); ok && r53err.Code() == "NoSuchHostedZone" {
return nil, fmt.Errorf("no such hosted zone")
return nil, r53NoHostedZoneFound
}
return nil, err
}
@ -310,9 +334,10 @@ func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceReco
if record.SetIdentifier != nil && *record.SetIdentifier != d.Get("set_identifier") {
continue
}
// The only safe return where a record is found
return record, nil
}
return nil, fmt.Errorf("nothing found")
return nil, r53NoRecordsFound
}
func resourceAwsRoute53RecordDelete(d *schema.ResourceData, meta interface{}) error {