[4-0-stable] Fix a bug where malformed query strings lead to 500

This is a backport of #16886.