In order to avoid a divide by zero with a numberSet (what you get after a reduction like avg()) you can short-circuit the logic:
$five = min(q("sum:rate{counter,,1}:haproxy.frontend.hrsp{}{status_code=5xx}", "1h", ""))
$two = avg(q("sum:rate{counter,,1}:haproxy.frontend.hrsp{}{status_code=2xx}", "1h", ""))
$five && $two / $five
If the above were just $two / $five
then when $five is zero, the result will be +Inf
which will cause an error when used as warn or crit value in an alert expression.