kemalcr / kemal

Fast, Effective, Simple Web Framework

Home Page:https://kemalcr.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`halt` as an exception

yujiri8 opened this issue · comments

Feature request (unless there's already something equivalent to this, but I couldn't find it)

My understanding is that halt is the only concise way of stopping execution to return a response, and that its use of next makes it impossible to use in helper functions, only in routes.

I'm looking at migrating to Kemal from FastAPI. In FastAPI, I can raise an HTTPException that stops the route handler to return a specified response. Since it works by raising an exception, I can use it anywhere.

Could halt or an alternative work the same way?

I don't see a way to use Kemal's exceptions to do what I need. The constructor for CustomException has only one overload that takes an HTTP::Server::Context. That means I'd have to set all the details such as status code and error message with separate statements before, which loses the conciseness of halt.

I did check out Grip when I was framework hunting, but I liked the way Kemal looks a lot more. OOP makes no sense to me in an HTTP framework. Kemal also has 25x the stars...

I don't see a way to use Kemal's exceptions to do what I need. The constructor for CustomException has only one overload that takes an HTTP::Server::Context. That means I'd have to set all the details such as status code and error message with separate statements before, which loses the conciseness of halt.

I did check out Grip when I was framework hunting, but I liked the way Kemal looks a lot more. OOP makes no sense to me in an HTTP framework. Kemal also has 25x the stars...

Grip is a fork of the Kemal framework, basically making it the same but with OOP

I've looked into this a little more. I can define a custom exception class that takes the required parameters, like:

class Exc < Exception
  def initialize(context : HTTP::Server::Context, code : Int, msg : String)
    super(msg)
    context.response.status_code = code
    context.response.print msg
  end
end

But the response is not sent; it sends a 500 with no message.

Oh! Nevermind I forgot context.response.close. This might work after all.