1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
|
# Copyright 2014 - present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use strict;
use warnings;
package MongoDB::Error;
# ABSTRACT: MongoDB Driver Error classes
# Portions adapted from Throwable.pm by Ricardo Signes
use version;
our $VERSION = 'v2.2.2';
use Moo;
use Carp;
use MongoDB::_Types qw(
ErrorStr
);
use Types::Standard qw(
ArrayRef
Str
);
use Scalar::Util ();
use Sub::Quote ();
use Safe::Isa;
use Exporter 5.57 qw/import/;
use namespace::clean -except => ['import'];
my $ERROR_CODES;
BEGIN {
$ERROR_CODES = {
BAD_VALUE => 2,
HOST_UNREACHABLE => 6,
HOST_NOT_FOUND => 7,
UNKNOWN_ERROR => 8,
USER_NOT_FOUND => 11,
ILLEGAL_OPERATION => 20,
NAMESPACE_NOT_FOUND => 26,
INDEX_NOT_FOUND => 27,
CURSOR_NOT_FOUND => 43,
EXCEEDED_TIME_LIMIT => 50,
COMMAND_NOT_FOUND => 59,
WRITE_CONCERN_ERROR => 64,
NETWORK_TIMEOUT => 89,
SHUTDOWN_IN_PROGRESS => 91,
PRIMARY_STEPPED_DOWN => 189,
SOCKET_EXCEPTION => 9001,
NOT_MASTER => 10107,
DUPLICATE_KEY => 11000,
DUPLICATE_KEY_UPDATE => 11001, # legacy before 2.6
INTERRUPTED_AT_SHUTDOWN => 11600,
INTERRUPTED_DUE_TO_REPL_STATE_CHANGE => 11602,
DUPLICATE_KEY_CAPPED => 12582, # legacy before 2.6
UNRECOGNIZED_COMMAND => 13390, # mongos error before 2.4
NOT_MASTER_NO_SLAVE_OK => 13435,
NOT_MASTER_OR_SECONDARY => 13436,
CANT_OPEN_DB_IN_READ_LOCK => 15927,
};
}
use constant $ERROR_CODES;
# Export error codes for use by end-users; this is unusual for Moo, but
# probably sufficiently helpful to justify it
our @EXPORT = keys %$ERROR_CODES;
our %_HORRIBLE_HACK;
use overload (
q{""} => sub {
my $self = shift;
return sprintf( "%s: %s", ref($self), $self->message );
},
fallback => 1
);
has message => (
is => 'ro',
isa => ErrorStr,
default => 'unspecified error',
);
has 'previous_exception' => (
is => 'ro',
default => Sub::Quote::quote_sub(q<
if (defined $MongoDB::Error::_HORRIBLE_HACK{ERROR}) {
$MongoDB::Error::_HORRIBLE_HACK{ERROR}
} elsif (defined $@ and (ref $@ or length $@)) {
$@;
} else {
undef;
}
>),
);
has error_labels => (
is => 'ro',
isa => ArrayRef[Str],
default => sub { [] },
);
sub has_error_label {
my ( $self, $expected ) = @_;
return unless defined $self->error_labels;
return grep { $_ eq $expected } @{ $self->error_labels };
}
sub add_error_label {
my ( $self, $label ) = @_;
return if $self->has_error_label( $label );
push @{ $self->error_labels }, $label;
}
sub throw {
my ($inv) = shift;
if (Scalar::Util::blessed($inv)) {
Carp::confess "throw called on MongoDB::Error object with arguments" if @_;
die $inv;
}
local $_HORRIBLE_HACK{ERROR} = $@;
my $throwable = @_ == 1 ? $inv->new( message => $_[0] ) : $inv->new(@_);
die $throwable;
}
# internal flag indicating if an operation should be retried when
# an error occurs.
sub _is_resumable { 1 }
# internal flag for if this error type specifically can be retried regardless
# of other state. See _is_retryable which contains the full retryable error
# logic.
sub __is_retryable_error { 0 }
my @retryable_codes = (
MongoDB::Error::HOST_NOT_FOUND(),
MongoDB::Error::HOST_UNREACHABLE(),
MongoDB::Error::NETWORK_TIMEOUT(),
MongoDB::Error::SHUTDOWN_IN_PROGRESS(),
MongoDB::Error::PRIMARY_STEPPED_DOWN(),
MongoDB::Error::SOCKET_EXCEPTION(),
MongoDB::Error::NOT_MASTER(),
MongoDB::Error::INTERRUPTED_AT_SHUTDOWN(),
MongoDB::Error::INTERRUPTED_DUE_TO_REPL_STATE_CHANGE(),
MongoDB::Error::NOT_MASTER_NO_SLAVE_OK(),
MongoDB::Error::NOT_MASTER_OR_SECONDARY(),
);
sub _check_is_retryable_code {
my $code = $_[-1];
return 1 if grep { $code == $_ } @retryable_codes;
return 0;
}
sub _check_is_retryable_message {
my $message = $_[-1];
return 0 unless defined $message;
return 1 if $message =~ /(not master|node is recovering)/i;
return 0;
}
# indicates if this error can be retried under retryable writes
sub _is_retryable {
my $self = shift;
if ( $self->$_can( 'result' ) ) {
return 1 if _check_is_retryable_code( $self->result->last_code );
}
if ( $self->$_can( 'code' ) ) {
return 1 if _check_is_retryable_code( $self->code );
}
return 1 if _check_is_retryable_message( $self->message );
if ( $self->$_isa( 'MongoDB::WriteConcernError' ) && $self->result->$_can( 'output' ) ) {
return 1 if _check_is_retryable_code( $self->result->output->{writeConcernError}{code} );
return 1 if _check_is_retryable_message( $self->result->output->{writeConcernError}{message} );
}
# Defaults to 0 unless its a network exception
return $self->__is_retryable_error;
}
my @unknown_commit_codes = (
MongoDB::Error::EXCEEDED_TIME_LIMIT(),
MongoDB::Error::WRITE_CONCERN_ERROR(),
);
sub _check_is_unknown_commit_code {
my $code = $_[-1];
return 1 if grep { $code == $_ } @unknown_commit_codes;
return 0;
}
sub _is_unknown_commit_error {
my $self = shift;
return 1 if $self->isa("MongoDB::ConnectionError") || $self->isa("MongoDB::SelectionError");
return 1 if $self->_is_retryable;
if ( $self->$_can( 'result' ) ) {
return 1 if _check_is_unknown_commit_code( $self->result->last_code );
}
if ( $self->$_can( 'code' ) ) {
return 1 if _check_is_unknown_commit_code( $self->code );
}
return 0;
}
sub _is_transient_transaction_error {
my $self = shift;
return 1 if $self->isa("MongoDB::ConnectionError") || $self->isa("MongoDB::SelectionError");
return 0;
}
# Look for error code ILLEGAL_OPERATION and starts with "Transaction numbers"
sub _is_storage_engine_not_retryable {
my $self = shift;
if ( $self->$_can( 'code' ) ) {
return 0 if $self->code != MongoDB::Error::ILLEGAL_OPERATION;
}
return index($self->message, "Transaction numbers", 0) == 0;
}
#--------------------------------------------------------------------------#
# Subclasses with attributes included inline below
#--------------------------------------------------------------------------#
package MongoDB::DatabaseError;
use Moo;
use MongoDB::_Types qw(
Numish
);
use namespace::clean;
extends("MongoDB::Error");
has result => (
is => 'ro',
does => 'MongoDB::Role::_DatabaseErrorThrower',
required => 1,
);
has code => (
is => 'ro',
isa => Numish,
builder => '_build_code',
);
sub _build_code { return MongoDB::Error::UNKNOWN_ERROR() }
sub _is_resumable { 0 }
package MongoDB::DocumentError;
use Moo;
use Types::Standard qw(Any);
use namespace::clean;
extends("MongoDB::Error");
has document => (
is => 'ro',
isa => Any,
required => 1,
);
package MongoDB::UsageError;
use Moo;
use Types::Standard qw(Str);
use namespace::clean -except => 'meta';
extends("MongoDB::Error");
use overload (
q{""} => sub {
my $self = shift;
return sprintf( "%s: %s%s", ref($self), $self->message, $self->trace );
},
fallback => 1
);
has trace => (
is => 'ro',
isa => Str,
);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
my $args = $class->SUPER::BUILDARGS(@_);
# start stack trace above where throw() is called (or
# at the top of the stack), so it works like confess
my $i = 0;
while ( my @caller = caller($i) ) {
$i++;
last if $caller[0] eq "MongoDB::Error";
}
local $Carp::CarpLevel = caller( $i + 1 ) ? $i + 1 : $i;
$args->{trace} = Carp::longmess('');
return $args;
};
# Connection errors
package MongoDB::ConnectionError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
sub _is_resumable { 1 }
sub __is_retryable_error { 1 }
package MongoDB::HandshakeError;
use Moo;
use namespace::clean;
extends 'MongoDB::ConnectionError';
package MongoDB::NetworkError;
use Moo;
use namespace::clean;
extends 'MongoDB::ConnectionError';
# Timeout errors
package MongoDB::TimeoutError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
sub __is_retryable_error { 1 }
package MongoDB::ExecutionTimeout;
use Moo;
use namespace::clean;
extends 'MongoDB::TimeoutError';
package MongoDB::NetworkTimeout;
use Moo;
use namespace::clean;
extends 'MongoDB::TimeoutError';
# Database errors
package MongoDB::DuplicateKeyError;
use Moo;
use namespace::clean;
extends 'MongoDB::DatabaseError';
sub _build_code { return MongoDB::Error::DUPLICATE_KEY() }
package MongoDB::NotMasterError;
use Moo;
use namespace::clean;
extends 'MongoDB::DatabaseError';
sub _build_code { return MongoDB::Error::NOT_MASTER() }
sub _is_resumable { 1 }
package MongoDB::WriteError;
use Moo;
use namespace::clean;
extends 'MongoDB::DatabaseError';
package MongoDB::WriteConcernError;
use Moo;
use namespace::clean;
extends 'MongoDB::DatabaseError';
sub _build_code { return MongoDB::Error::WRITE_CONCERN_ERROR() }
# Other errors
package MongoDB::AuthError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::ConfigurationError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::CursorNotFoundError;
use Moo;
use namespace::clean;
extends 'MongoDB::DatabaseError';
sub _build_code { return MongoDB::Error::CURSOR_NOT_FOUND() }
sub _is_resumable { 1 }
package MongoDB::DecodingError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::GridFSError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::InternalError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::ProtocolError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::SelectionError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
package MongoDB::InvalidOperationError;
use Moo;
use namespace::clean;
extends 'MongoDB::Error';
#--------------------------------------------------------------------------#
# Private error classes
#--------------------------------------------------------------------------#
package MongoDB::_CommandSizeError;
use Moo;
use MongoDB::_Types qw(
Intish
);
use namespace::clean;
extends("MongoDB::Error");
has size => (
is => 'ro',
isa => Intish,
required => 1,
);
1;
=pod
=encoding UTF-8
=head1 NAME
MongoDB::Error - MongoDB Driver Error classes
=head1 VERSION
version v2.2.2
=head1 SYNOPSIS
use MongoDB::Error;
MongoDB::Error->throw("a generic error");
MongoDB::DatabaseError->throw(
message => $string,
result => $hashref,
);
=head1 DESCRIPTION
This class defines a hierarchy of exception objects.
=head1 USAGE
Unless otherwise explicitly documented, all driver methods throw exceptions if
an error occurs.
To catch and handle errors, the L<Try::Tiny> and L<Safe::Isa> modules
are recommended:
use Try::Tiny;
use Safe::Isa; # provides $_isa
try {
$coll->insert( $doc )
}
catch {
if ( $_->$_isa("MongoDB::DuplicateKeyError" ) ) {
...
}
else {
...
}
};
To retry failures automatically, consider using L<Try::Tiny::Retry>.
=head1 EXCEPTION HIERARCHY
MongoDB::Error
|
|->MongoDB::AuthError
|
|->MongoDB::ConnectionError
| |
| |->MongoDB::HandshakeError
| |
| |->MongoDB::NetworkError
|
|->MongoDB::ConfigurationError
|
|->MongoDB::DatabaseError
| |
| |->MongoDB::CursorNotFoundError
| |
| |->MongoDB::DuplicateKeyError
| |
| |->MongoDB::NotMasterError
| |
| |->MongoDB::WriteError
| |
| |->MongoDB::WriteConcernError
|
|->MongoDB::DecodingError
|
|->MongoDB::DocumentError
|
|->MongoDB::GridFSError
|
|->MongoDB::InternalError
|
|->MongoDB::InvalidOperationError
|
|->MongoDB::ProtocolError
|
|->MongoDB::SelectionError
|
|->MongoDB::TimeoutError
| |
| |->MongoDB::ExecutionTimeout
| |
| |->MongoDB::NetworkTimeout
|
|->MongoDB::UsageError
All classes inherit from C<MongoDB::Error>.
All error classes have the attribute:
=over 4
=item *
message — a text representation of the error
=back
=head2 MongoDB::AuthError
This error indicates a problem with authentication, either in the underlying
mechanism or a problem authenticating with the server.
=head2 MongoDB::ConnectionError
Errors related to network connections.
=head3 MongoDB::HandshakeError
This error is thrown when a connection has been made, but SSL or authentication
handshakes fail.
=head3 MongoDB::NetworkError
This error is thrown when a socket error occurs, when the wrong number of bytes
are read, or other wire-related errors occur.
=head2 MongoDB::ConfigurationError
This error is thrown when there is a configuration error between the MongoDB
deployment and the configuration of the client, such as when trying to use
explicit sessions on a MongoDB < 3.6
=head2 MongoDB::CursorNotFoundError
This error indicates that a cursor timed out on a server.
=head2 MongoDB::DatabaseError
Errors related to database operations. Specifically, when an error of this type
occurs, the driver has received an error condition from the server.
Attributes include:
=over 4
=item *
result — response from a database command; this must implement the C<last_errmsg> method
=item *
code — numeric error code; see L</ERROR CODES>; if no code was provided by the database, the C<UNKNOWN_ERROR> code will be substituted instead
=back
=head3 MongoDB::DuplicateKeyError
This error indicates that a write attempted to create a document with a
duplicate key in a collection with a unique index. The C<result> attribute is
a result object.
=head3 MongoDB::NotMasterError
This error indicates that a write or other state-modifying operation was
attempted on a server that was not a primary. The C<result> attribute is
a L<MongoDB::CommandResult> object.
=head3 MongoDB::WriteError
Errors indicating failure of a write command. The C<result> attribute is
a result object.
=head3 MongoDB::WriteConcernError
Errors indicating failure of a write concern. The C<result> attribute is a
result object.
=head2 MongoDB::DecodingError
This error indicates a problem during BSON decoding; it wraps
the error provided by the underlying BSON encoder. Note: Encoding errors
will be thrown as a L</MongoDB::DocumentError>.
=head2 MongoDB::DocumentError
This error indicates a problem with a document to be inserted or replaced into
the database, or used as an update document.
Attributes include:
=over 4
=item *
document — the document that caused the error
=back
=head2 MongoDB::GridFSError
Errors related to GridFS operations, such a corrupted file.
=head2 MongoDB::InternalError
Errors that indicate problems in the driver itself, typically when something
unexpected is detected. These should be reported as potential bugs.
=head2 MongoDB::ProtocolError
Errors related to the MongoDB wire protocol, typically problems parsing a
database response packet.
=head2 MongoDB::SelectionError
When server selection fails for a given operation, this is thrown. For example,
attempting a write when no primary is available or reading with a specific mode
and tag set and no servers match.
=head2 MongoDB::TimeoutError
These errors indicate a user-specified timeout has been exceeded.
=head3 MongoDB::ExecutionTimeout
This error is thrown when a query or command fails because C<max_time_ms> has
been reached. The C<result> attribute is a L<MongoDB::CommandResult> object.
=head3 MongoDB::NetworkTimeout
This error is thrown when a network operation exceeds a timeout, typically
C<connect_timeout_ms> or C<socket_timeout_ms>.
=head2 MongoDB::UsageError
Indicates invalid arguments or configuration options. Not all usage errors
will throw this — only ones originating directly from the MongoDB::* library
files. Some type and usage errors will originate from the L<Type::Tiny>
library if the objects are used incorrectly.
Also used to indicate usage errors for transaction commands.
=head1 ERROR CODES
The following error code constants are automatically exported by this module.
BAD_VALUE => 2,
UNKNOWN_ERROR => 8,
NAMESPACE_NOT_FOUND => 26,
EXCEEDED_TIME_LIMIT => 50,
COMMAND_NOT_FOUND => 59,
WRITE_CONCERN_ERROR => 64,
NOT_MASTER => 10107,
DUPLICATE_KEY => 11000,
DUPLICATE_KEY_UPDATE => 11001, # legacy before 2.6
DUPLICATE_KEY_CAPPED => 12582, # legacy before 2.6
UNRECOGNIZED_COMMAND => 13390, # mongos error before 2.4
NOT_MASTER_NO_SLAVE_OK => 13435,
NOT_MASTER_OR_SECONDARY => 13436,
CANT_OPEN_DB_IN_READ_LOCK => 15927,
This is a very, very small subset of error codes possible from the server,
but covers some of the more common ones seen by drivers.
B<Note>:
=over 4
=item *
Only C<MongoDB::DatabaseError> objects have a C<code> attribute.
=item *
The database uses multiple write concern error codes. The driver maps them all to WRITE_CONCERN_ERROR for consistency and convenience.
=back
=head1 ERROR LABELS
From MongoDB 4.0 onwards, errors may contain an error labels field. This field
is populated for extra information from either the server or the driver,
depending on the error.
Known error labels include (but are not limited to):
=over 4
=item *
C<TransientTransactionError> - added when network errors are encountered inside a transaction.
=item *
C<UnknownTransactionCommitResult> - added when a transaction commit may not have been able to satisfy the provided write concern.
=back
=head1 AUTHORS
=over 4
=item *
David Golden <david@mongodb.com>
=item *
Rassi <rassi@mongodb.com>
=item *
Mike Friedman <friedo@friedo.com>
=item *
Kristina Chodorow <k.chodorow@gmail.com>
=item *
Florian Ragwitz <rafl@debian.org>
=back
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2020 by MongoDB, Inc.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
=cut
__END__
# vim: ts=4 sts=4 sw=4 et:
|