'Fix a bug where malformed query strings lead to 500

This is a backport PR of #16871 to `4-0-stable`.