Move middleware setting, improve exception message.