Skip to content

Commit

Permalink
[ENH] give more meaningful error messsages when failing to read json (#…
Browse files Browse the repository at this point in the history
…582)

* add warning mentioning which json files could not be read

* add file not found erro
  • Loading branch information
Remi-Gau authored Jun 18, 2023
1 parent df0c543 commit db6e3d0
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
34 changes: 31 additions & 3 deletions +bids/+util/jsondecode.m
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,48 @@
ismember(exist('jsondecode', 'file'), [2 3]); % jsonstuff / Matlab-compatible implementation
end

if ~exist(file, 'file')
msg = sprintf('Unable to read file ''%s'': file not found', file);
bids.internal.error_handling(mfilename(), 'FileNotFound', ...
msg, false);
end

if has_jsondecode
value = jsondecode(fileread(file));
try
value = jsondecode(fileread(file));
catch ME
warning_cannot_read_json(file);
rethrow(ME);
end

% JSONio
elseif exist('jsonread', 'file') == 3
value = jsonread(file, varargin{:});
try
value = jsonread(file, varargin{:});
catch ME
warning_cannot_read_json(file);
rethrow(ME);
end

% SPM12
elseif exist('spm_jsonread', 'file') == 3
value = spm_jsonread(file, varargin{:});
try
value = spm_jsonread(file, varargin{:});
catch ME
warning_cannot_read_json(file);
rethrow(ME);
end

else
url = 'https://github.com/gllmflndn/JSONio';
error('JSON library required: install JSONio from: %s', url);

end

end

function warning_cannot_read_json(file)
msg = sprintf('Could not read file:\n%s', file);
bids.internal.error_handling(mfilename(), 'CannotReadJson', ...
msg, true, true);
end
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
miss_hit==0.9.35
miss_hit
pre-commit
jupyterlab
octave_kernel
Expand Down
31 changes: 31 additions & 0 deletions tests/tests_utils/test_json_decode.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function test_suite = test_json_decode %#ok<*STOUT>
try % assignment of 'localfunctions' is necessary in Matlab >= 2016
test_functions = localfunctions(); %#ok<*NASGU>
catch % no problem; early Matlab versions can use initTestSuite fine
end
initTestSuite;
end

function test_json_decode_file_not_found()

% write dummy faulty json

filename = fullfile(temp_dir, 'foo.json');
assertExceptionThrown(@() bids.util.jsondecode(filename), ...
'jsondecode:FileNotFound');

end

function test_json_decode_parse_error()

% write dummy faulty json

filename = fullfile(temp_dir, 'wrong.json');
fid = fopen(filename, 'Wt');
fprintf(fid, '{"foo": "bla"');
fclose(fid);

assertWarning(@() bids.util.jsondecode(filename), ...
'jsondecode:CannotReadJson');

end

0 comments on commit db6e3d0

Please sign in to comment.