function [isMvmException, parException] = transformIfMvmException(e)
%transformIfMvmException Transform Java MvmException instances into ParallelException
%   [isMvmException, parException] = transformIfMvmException(E) transforms java
%   exception E into ParallelException parException if
%   possible. isMvmException is true when E is indeed an instance of
%   MvmException, false otherwise.

% Copyright 2018 The MathWorks, Inc.

% Default to true - will be set back to false later.
isMvmException = true;

if isa(e, 'com.mathworks.mvm.exec.MvmExecutionException')
    % Unpick the 'MvmCause'
    mvmE = e.getMvmCause();
    parException = iParExceptionFromMvmException(mvmE);
elseif isa(e, 'com.mathworks.mvm.exec.MvmInterruptedException')
    % Execution was interrupted
    parException = ParallelException.hBuildLikeMException(...
        message('MATLAB:interrupt'));
elseif isa(e, 'com.mathworks.mvm.exec.MvmException')
    % Got down to the MvmException directly
    parException = iParExceptionFromMvmException(e);
else
    % Not an MvmException
    isMvmException = false;
    parException = [];
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function E = iParExceptionFromMvmException(e)
E = ParallelException.hBuildLikeMException(...
    string(e.getID()), ...
    '%s', string(e.getLocalizedMessage()));
end
