Refactor to handle errors and consistency between controller and db