Move JSON output handling to middleware; improved error handling