The Crystal Programming Language Forum

Accepting integer parameter in Kemal - error handling

In the web application I am writing I expect an optional parameter called size that is expected to be an integer. I would like to default it to 10 and disregard any bad (non integer input) I came up with this expression:

size = begin env.params.query["size"].to_i rescue 10 end

Is there a better way to write it?

As I was writing this post it occurred to me that size should be a non-negative integer so the above expression is not really good, but I’d still be interested in the answer to the above and maybe to the version where we only accept it when it is a non-negative.

Probably could just do like env.params.query["size"].to_i? || 10? I didn’t test it but pretty sure that should work.

Best bet here would be to return some type of error response size < 0, I wouldn’t really advise casting it into an unsigned int for validation reasons.

Thanks.

What is the meaning of that question mark after the number 10? I don’t understand that and when I try to copy this expression Crystal won’t compile.

Without that ? the code compiles but if no size parameter is provided then it raises an exception: “Missing param name: “size” (KeyError)”

It wasn’t part of the code, was the punctuation to my sentence.

Ah, try like env.params.query["size"]?.try(&.to_i?) || 10 in that case.