Skip to content

Commit ed5a2f0

Browse files
committed
feat(problems): add more context to the default text response
1 parent 894c1ac commit ed5a2f0

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

problem.go

+21-1
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,28 @@ func ProblemControlsResponseFrom(responses map[string]Builder) ProblemControlsRe
262262
}
263263
}
264264

265+
textResponse := fmt.Sprintf(
266+
"%d %s\n\n%s",
267+
problem.Status,
268+
problem.Title,
269+
problem.Detail,
270+
)
271+
272+
controls := problem.controls(request)
273+
274+
errors, found := problem.Additional(controls.ErrorsKey(problem, request))
275+
traces, tracesOK := errors.([]string)
276+
277+
if found && tracesOK && controls.Errors(problem, request) {
278+
textResponse += fmt.Sprintf("\n\n")
279+
280+
for _, trace := range traces {
281+
textResponse += fmt.Sprintf("%s\n", trace)
282+
}
283+
}
284+
265285
return Response(problem.Status).
266-
Text(fmt.Sprintf("%d %s\n\n%s", problem.Status, problem.Title, problem.Detail))
286+
Text(textResponse)
267287
}
268288
}
269289

problem_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
"net/http"
8+
"strings"
89
"testing"
910

1011
"github.com/studiolambda/akumu"
@@ -163,6 +164,21 @@ func TestProblemWithCustomError(t *testing.T) {
163164
}
164165
}
165166

167+
func TestProblemWithCustomError2(t *testing.T) {
168+
request, err := http.NewRequest("GET", "/", nil)
169+
170+
if err != nil {
171+
t.Fatalf("unable to create request: %s", err)
172+
}
173+
174+
response := akumu.Record(customProblemHandlerWithErr, request)
175+
res := string(response.Body.Bytes())
176+
177+
if expect := "last error: failed"; !strings.Contains(res, expect) {
178+
t.Fatalf("error should contain '%s'", expect)
179+
}
180+
}
181+
166182
func TestProblemDirectError(t *testing.T) {
167183
request, err := http.NewRequest("GET", "/", nil)
168184

0 commit comments

Comments
 (0)