Is it possible to exit from a Kemal route earlier based on some condition without using halt
? For example, can I do something like:
post "/someroute" do |env|
if not_cond_satisfied
exit here
end
do some processing here. Reaches this part only if cond_satisfied.
end
-
I know that one can add an else statement before do some processing...
. However, this is a simple example. I would have too many nested if-else
statements in what I want to do, and hence would prefer to do this in the manner above if possible.
-
I know about halt env status_code reason
. However, that allows me to only send a string
as reason. I would ideally like to send json
because that is what I send if everything is successful.
Thank you.
I mean halt
is the way to do this. JSON is just a string anyway, why not just return a JSON string via halt
?
Something like
halt env, 400, %({"code":400,"message":"Some message"})
Whats the use case here? Some JSON API? If you’re checking for like auth headers or something, it might be better to do this in a handler so that you wouldn’t have to duplicate it within every route.
EDIT: You could also define your own macro like halt that also adds an application/json
content type header.
You can use next
to exit early from a block.
I am using a server, say uploader
to perform file uploads (check a few things and then save the files that are sent to it if checks pass). Another server, say requester
will make requests to uploader
by sending files to it. I want the uploader
to send a json response to the requester
about what happened. Example: {type: “error”, msg: “Upload failed because of problem X”} or {type: “error”, msg: “Upload failed because of problem Y”}. I think your string solution should work. I will try it.
Thank you.
1 Like