refactored database error handling