function parallelExcept = pWrapExceptionsIntoParallelException(excepts, labsStr)
% Private helper that creates generic SPMD error, add all excepts as cause
% and as remote cause.

% Copyright 2019 The MathWorks, Inc.

singleExcept = numel(excepts) == 1;
if singleExcept
    errorID = 'parallel:lang:spmd:ExecutionErrorSingleWorker';
else
    errorID = 'parallel:lang:spmd:ExecutionError';
    
    % As per g1507414, attempt to simplify the output in the (common) case
    % where all of 'excepts' are identical.
    if all(cellfun(@(e) isequal(e, excepts{1}), excepts(2:end)))
        excepts = excepts(1);
    end
end

parallelExcept = ParallelException.hBuildLikeMException(message(errorID, labsStr));

for ii=1:length( excepts )
    parallelExcept = addCause(parallelExcept, excepts{ii});
    parallelExcept = hAddRemoteCause(parallelExcept, excepts{ii});
end
end