From ff62b732fc167d11060f320384ca910ef8da0ae7 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Mon, 18 Dec 2017 13:48:56 -0300 Subject: [PATCH] Bug 19828: Make Koha::Object->store translate DBIC exceptions into Koha exceptions This patch introduces a try/catch block in store() and parses the error when an exceptional situation takes place. It only deals with FK constraint violations. The rest of the DBIC exceptions are rethrown. To test: - Apply this patch - Run: $ kshell k$ prove t/db_dependent/Koha/Object.t => SUCCESS: Tests pass! - Sign off :-D --- Koha/Exceptions/Object.pm | 5 +++++ Koha/Object.pm | 28 +++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Koha/Exceptions/Object.pm b/Koha/Exceptions/Object.pm index 2ffa1ec851..f2763a43a8 100644 --- a/Koha/Exceptions/Object.pm +++ b/Koha/Exceptions/Object.pm @@ -7,6 +7,11 @@ use Exception::Class ( 'Koha::Exceptions::Object' => { description => 'Something went wrong!', }, + 'Koha::Exceptions::Object::FKConstraint' => { + isa => 'Koha::Exceptions::Object', + description => "Foreign key constraint broken", + fields => ['broken_fk'] + }, 'Koha::Exceptions::Object::MethodNotFound' => { isa => 'Koha::Exceptions::Object', description => "Invalid method", diff --git a/Koha/Object.pm b/Koha/Object.pm index fc30adc2b3..bcf6fd383a 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -22,6 +22,7 @@ use Modern::Perl; use Carp; use Mojo::JSON; +use Try::Tiny; use Koha::Database; use Koha::Exceptions::Object; @@ -119,7 +120,32 @@ Returns: sub store { my ($self) = @_; - return $self->_result()->update_or_insert() ? $self : undef; + try { + return $self->_result()->update_or_insert() ? $self : undef; + } + catch { + # Catch problems and raise relevant exceptions + if (ref($_) eq 'DBIx::Class::Exception') { + if ( $_->{msg} =~ /Cannot add or update a child row: a foreign key constraint fails/ ) { + # FK constraints + # FIXME: MySQL error, if we support more DB engines we should implement this for each + if ( $_->{msg} =~ /FOREIGN KEY \(`(?.*?)`\)/ ) { + Koha::Exceptions::Object::FKConstraint->throw( + error => 'Broken FK constraint', + broken_fk => $+{column} + ); + } + else { + # Catch-all for foreign key breakages. It will help find other use cases + $->rethrow(); + } + } + else { + # TODO: find other exceptions we could handle + $->rethrow(); + } + } + } } =head3 $object->delete(); -- 2.14.1