From 60b03c028bad04aa2b8677e269aa6b3d69d3dc62 Mon Sep 17 00:00:00 2001 From: Jonathan Druart Date: Tue, 24 Jan 2023 12:22:16 +0100 Subject: [PATCH] Bug 32709: Prevent REST API and UI to crash if job has incorrect JSON Same as bug 32393, but for the REST API routes and the UI. Test plan: Enqueue a job with an incorrect JSON string in the data column Go to the background jobs list and the detail views Confirm that no the page does not explodes Notice the warning on the detail page --- Koha/BackgroundJob.pm | 31 ++++++++++++------- .../prog/en/modules/admin/background_jobs.tt | 7 +++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/Koha/BackgroundJob.pm b/Koha/BackgroundJob.pm index 727bc3b2f7b..0abf0706608 100644 --- a/Koha/BackgroundJob.pm +++ b/Koha/BackgroundJob.pm @@ -284,7 +284,14 @@ Returns the decoded JSON contents from $self->data. sub decoded_data { my ($self) = @_; - return $self->data ? $self->json->decode( $self->data ) : undef; + return try { + $self->json->decode( $self->data ); + } catch { + Koha::Logger->get->warn( + sprintf "Cannot decode data for background job id=%s", + $self->id ); + undef; + }; } =head3 set_encoded_data @@ -316,15 +323,12 @@ Messages let during the processing of the job. =cut sub messages { - my ( $self ) = @_; + my ($self) = @_; - my @messages; - my $data_dump = $self->json->decode($self->data); - if ( exists $data_dump->{messages} ) { - @messages = @{ $data_dump->{messages} }; - } + my $data_dump = $self->decoded_data; - return \@messages; + return $data_dump + && exists $data_dump->{messages} ? $data_dump->{messages} : []; } =head3 report @@ -334,10 +338,12 @@ Report of the job. =cut sub report { - my ( $self ) = @_; + my ($self) = @_; - my $data_dump = $self->json->decode($self->data); - return $data_dump->{report} || {}; + my $data_dump = $self->decoded_data; + + return $data_dump + && exists $data_dump->{report} ? $data_dump->{report} : {}; } =head3 additional_report @@ -491,7 +497,8 @@ sub to_api { $json->{context} = $self->json->decode($self->context) if defined $self->context; - $json->{data} = $self->decoded_data; + + $json->{data} = $self->decoded_data || {}; return $json; } diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/background_jobs.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/background_jobs.tt index f65d8189f90..693d382097c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/background_jobs.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/background_jobs.tt @@ -102,6 +102,13 @@

Report

+ [% UNLESS job.decoded_data %] +
+ Something terribly wrong happened with this job. + The data cannot be decoded: [% job.data %] +
+ [% END %] + [% IF job.status != 'new' %][% PROCESS 'report' %][% END %]
-- 2.25.1