Skip to content

The current implementation of build_json requires that no exceptions be thrown #24

@dscottboggs

Description

@dscottboggs

The current implementation of build_json requires that no exceptions be thrown while the response is being built. Until now, the only resolution to this I could think of was building to an intermediary IO and copying to context.response after it's built. That would be a big performance hit in a crucial spot. However, talking another look at my implementation I was thinking that there is one alternative, although it is less than ideal....suggestions are welcome, but I'd recommend we discuss this in a separate PR, so that I can also begin work on other routes while we work out the details.

def build_json(response : IO)
  error : Exception? = nil
  JSON.build response do |json|
    json.object do
      json.field "data" do
        json.object do
          yield json
        rescue e
          error = e
        end
      end
      if error
        json.field "errors" do
          ErrorResponse.new(error).errors.to_json json
        end
      end
    end
  end
end

I realize this would require specifying a partial succesful response, but there's no way to rewind an HTTP::Server::Response because it's streamed out to the client on the fly.

Originally posted by @dscottboggs in #10

For the package routes, I (think) I successfully avoided cases which raise, so that's an option as well, but it's...fragile, and I don't like it, especially not long-term

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions