diff --git a/Koha/Exceptions/Object.pm b/Koha/Exceptions/Object.pm index dd79cee90c..4181675826 100644 --- a/Koha/Exceptions/Object.pm +++ b/Koha/Exceptions/Object.pm @@ -33,6 +33,11 @@ use Exception::Class ( description => "Foreign key constraint broken", fields => ['broken_fk', 'value'], }, + 'Koha::Exceptions::Object::FKConstraintDeletion' => { + isa => 'Koha::Exceptions::Object', + description => "Foreign key constraint broken on deleting resource", + fields => [ 'column', 'fk', 'table', 'constraint' ], + }, 'Koha::Exceptions::Object::MethodNotFound' => { isa => 'Koha::Exceptions::Object', description => "Invalid method", diff --git a/Koha/Object.pm b/Koha/Object.pm index a833f30580..ad34bbc948 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -233,11 +233,32 @@ Returns: sub delete { my ($self) = @_; - my $deleted = $self->_result()->delete; + my $deleted; + + try { + $deleted = $self->_result()->delete; + } catch { + if ( ref($_) eq 'DBIx::Class::Exception' ) { + if ( $_->{msg} =~ + /Cannot delete or update a parent row\: a foreign key constraint fails \(\`(?.*?)\`\.\`(?.*?)\`, CONSTRAINT \`(?.*?)\` FOREIGN KEY \(\`(?.*?)\`\) REFERENCES \`.*\` \(\`(?.*?)\`\)/ + ) + { + Koha::Exceptions::Object::FKConstraintDeletion->throw( + column => $+{column}, + constraint => $+{constraint}, + fk => $+{fk}, + table => $+{table}, + ); + } + $_->rethrow(); + } + }; + if ( ref $deleted ) { - my $object_class = Koha::Object::_get_object_class( $self->_result->result_class ); + my $object_class = Koha::Object::_get_object_class( $self->_result->result_class ); $deleted = $object_class->_new_from_dbic($deleted); } + return $deleted; }