refactor config/middleware and update 404/500 handling