Middleware and API error handling