Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make DefaultProblem implement the error interface #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go:
- 1.5
- 1.6
- 1.6.2
- release
- 1.7
- tip

script:
Expand Down
9 changes: 9 additions & 0 deletions problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package problems

import (
"errors"
"fmt"
"net/http"
"net/url"
)
Expand All @@ -24,6 +25,7 @@ const (
type Problem interface {
ProblemType() (*url.URL, error)
ProblemTitle() string
Error() string
}

// StatusProblem is the interface describing a problem with an associated
Expand Down Expand Up @@ -119,3 +121,10 @@ func (p *DefaultProblem) ProblemTitle() string {
func (p *DefaultProblem) ProblemStatus() int {
return p.Status
}

// Implement Error() so it can satisfy the default error Interface
// It returns a string in the form of:
// <Title> (Status) - <Detail>
func (p *DefaultProblem) Error() string {
return fmt.Sprintf("%s (%d) - %s", p.Title, p.Status, p.Detail)
}
25 changes: 25 additions & 0 deletions problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ func (p badProblemType) ProblemTitle() string {
return "something valid"
}

func (p badProblemType) Error() string {
return ""
}

type badProblemTitle struct{}

func (p badProblemTitle) ProblemType() (*url.URL, error) {
Expand All @@ -52,6 +56,10 @@ func (p badProblemTitle) ProblemTitle() string {
return ""
}

func (p badProblemTitle) Error() string {
return ""
}

func TestValidateProblem(t *testing.T) {
var err error
err = ValidateProblem(badProblemType{})
Expand Down Expand Up @@ -118,3 +126,20 @@ func TestCreditProblem(t *testing.T) {
t.Errorf("problem is not valid")
}
}

func TestErrorInterface(t *testing.T) {
var i interface{} = &DefaultProblem{Type: DefaultURL,
Status: 401,
Title: http.StatusText(http.StatusUnauthorized),
Detail: "Detail Message.",
}
p, ok := i.(error)
if !ok {
t.Errorf("DefaultProblem does not implement error interface")
}

expected := http.StatusText(http.StatusUnauthorized) + " (401) - Detail Message."
if p.Error() != expected {
t.Errorf("Error message was not what we were expecting. Expected '%s', got '%s'", expected, p.Error())
}
}