Skip to content

[PROPOSAL] returning interface from handlers #96

@karitham

Description

@karitham

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions