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 and duplicate IDs. 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

Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>

Signed-off-by: Josef Moravec <josef.moravec@gmail.com>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
This commit is contained in:
Tomas Cohen Arazi 2017-12-18 13:48:56 -03:00 committed by Jonathan Druart
parent 122f544132
commit 84a8f09ec2
2 changed files with 37 additions and 1 deletions

View File

@ -7,6 +7,16 @@ use Exception::Class (
'Koha::Exceptions::Object' => {
description => 'Something went wrong!',
},
'Koha::Exceptions::Object::DuplicateID' => {
isa => 'Koha::Exceptions::Object',
description => "Duplicate ID passed",
fields => ['duplicate_id']
},
'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",

View File

@ -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 \(`(?<column>.*?)`\)/ ) {
Koha::Exceptions::Object::FKConstraint->throw(
error => 'Broken FK constraint',
broken_fk => $+{column}
);
}
}
elsif( $_->{msg} =~ /Duplicate entry '(.*?)' for key '(?<key>.*?)'/ ) {
Koha::Exceptions::Object::DuplicateID->throw(
error => 'Duplicate ID',
duplicate_id => $+{key}
);
}
# Catch-all for foreign key breakages. It will help find other use cases
$->rethrow();
}
}
}
=head3 $object->delete();