Refactor response handling logic into middleware