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

[PROPOSAL] returning interface from handlers #96

Open
karitham opened this issue Aug 3, 2022 · 0 comments
Open

[PROPOSAL] returning interface from handlers #96

karitham opened this issue Aug 3, 2022 · 0 comments

Comments

@karitham
Copy link
Collaborator

karitham commented Aug 3, 2022

Right now, returning concrete types is nice for well defined return types, such as 200s, but once you want to return simple errors, it becomes a pain.

For example, let's say I want to return an InternalServerError with an error code and clarification.

With the status quo, this looks like:

	return CreateThingJSONDefaultResponse(
		DefaultResponse{Code: "spiky-sun-turtle", Message: http.StatusText(http.StatusInternalServerError)},
	).Status(500)

This gets really verbose really fast.
What we could have instead is

type InternalServerError struct {
    Code    string `json:"code"`
    Message string `json:"message"`
}

func (e InternalServerError) Respond() *Response {
    return Response{Code: 500, Body: e, ContentType: "application/json"}
}

and use it like so:

return InternalServerError{Code: "goop-turtle", Message: http.StatusText(http.StatusInternalServerError)}

Any type implementing

type Responder interface {
     Respond() *Response
}

Could be returned, thus easily implementing custom errors in a much less verbose way.

This would also allow us to have possible hooks in responses, to avoid having more telemetry/logging directly in the handler, since those types could only wrap parts intended for the users, while we could abstract the telemetry to our own functions, thus making error handling go from 5/7 lines per error to 1 or 2.

@karitham karitham linked a pull request Aug 15, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant