chore: Linter rule for properly formatted api errors (#2123)

* chore: Linter rule for properly formatted api errors
* Add omitempty to 'Detail' field
This commit is contained in:
Steven Masley
2022-06-07 09:33:06 -05:00
committed by GitHub
parent 3f1e885d21
commit af401e3fe1
37 changed files with 351 additions and 302 deletions
+35
View File
@@ -115,3 +115,38 @@ func InTx(m dsl.Matcher) {
`).Where(m["x"].Text != m["y"].Text).
At(m["f"]).Report("Pass the tx database into the '$f' function inside the closure. Use '$y' over $x'")
}
// HttpAPIErrorMessage intends to enforce constructing proper sentences as
// error messages for the api. A proper sentence includes proper capitalization
// and ends with punctuation.
// There are ways around the linter, but this should work in the common cases.
func HttpAPIErrorMessage(m dsl.Matcher) {
m.Import("github.com/coder/coder/coderd/httpapi")
isNotProperError := func(v dsl.Var) bool {
return v.Type.Is("string") &&
// Either starts with a lowercase, or ends without punctuation.
// The reason I don't check for NOT ^[A-Z].*[.!?]$ is because there
// are some exceptions. Any string starting with a formatting
// directive (%s) for example is exempt.
(m["m"].Text.Matches(`^"[a-z].*`) ||
m["m"].Text.Matches(`.*[^.!?]"$`))
}
m.Match(`
httpapi.Write($_, $s, httpapi.Response{
$*_,
Message: $m,
$*_,
})
`, `
httpapi.Write($_, $s, httpapi.Response{
$*_,
Message: fmt.$f($m, $*_),
$*_,
})
`,
).Where(isNotProperError(m["m"])).
At(m["m"]).
Report("Field \"Message\" should be a proper sentence with a capitalized first letter and ending in punctuation. $m")
}