added next function and error handling