Added middleware/fixed error handling