Check if an exception is caused by a MySQL exception of certain error code
192256
private static boolean mySqlErrorCodeMatches(Exception e, int errorCode)
    {
        return Throwables.getCausalChain(e).stream()
                .filter(SQLException.class::isInstance)
                .map(SQLException.class::cast)
                .filter(t -> t.getErrorCode() == errorCode)
                .map(Throwable::getStackTrace)
                .anyMatch(isMySQLException());
    }
1333141
def execute_catch(c, sql, vars=None):
    """"""
    try:
        c.execute(sql, vars)
    except Exception as err:
        cmd = sql.split(' ', 1)[0]
        log.error("Error executing %s: %s", cmd, err)
1199666
public boolean isConstraintError(SQLException e) {
        if (e != null) {
            String sqlstate = e.getSQLState();
            if (sqlstate != null) {
                return sqlstate.startsWith(SQLSTATE_CONSTRAINT_VIOLATION_CLASS_CODE);
            }
        }
        return false;
    }
848036
def is_connection_error(e):
    
    return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
        (isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values())
687898
def _error_check(err, prefix=""):
    """"""
    if err != 0:
        err_str = _snd.sf_error_number(err)
        raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
1177455
def _incr_exceptions(self):
        """"""
        self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
441099
private boolean isSQLErrorTransient(SQLException sqlex) {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "isSQLErrorTransient ", new Object[] { sqlex, this });
        boolean retryBatch = false;
        int sqlErrorCode = sqlex.getErrorCode();

        if (tc.isEventEnabled()) {
            Tr.event(tc, " SQL exception:");
            Tr.event(tc, " Message: " + sqlex.getMessage());
            Tr.event(tc, " SQLSTATE: " + sqlex.getSQLState());
            Tr.event(tc, " Error code: " + sqlErrorCode);
        }

        for (int transientCode : _sqlTransientErrorCodes) {
            Tr.event(tc, "Test against stored code: " + transientCode);
            if (transientCode == sqlErrorCode) {
                Tr.event(tc, "TRANSIENT: A connection failed but could be reestablished, retry.");
                retryBatch = true;
                break;
            }
        }

        if (!retryBatch && sqlex instanceof BatchUpdateException) {
            BatchUpdateException buex = (BatchUpdateException) sqlex;
            Tr.event(tc, "BatchUpdateException: Update Counts - ");
            int[] updateCounts = buex.getUpdateCounts();
            for (int i = 0; i < updateCounts.length; i++) {
                Tr.event(tc, "   Statement " + i + ":" + updateCounts[i]);
            }
            SQLException nextex = buex.getNextException();
            while (nextex != null) {
                sqlErrorCode = nextex.getErrorCode();
                if (tc.isEventEnabled()) {
                    Tr.event(tc, " SQL exception:");
                    Tr.event(tc, " Message: " + nextex.getMessage());
                    Tr.event(tc, " SQLSTATE: " + nextex.getSQLState());

                    Tr.event(tc, " Error code: " + sqlErrorCode);
                }

                for (int transientCode : _sqlTransientErrorCodes) {
                    Tr.event(tc, "Test against stored code: " + transientCode);
                    if (transientCode == sqlErrorCode) {
                        Tr.event(tc, "TRANSIENT: A connection failed but could be reestablished, retry.");
                        retryBatch = true;
                        break;
                    }
                }

                nextex = nextex.getNextException();
            }
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "isSQLErrorTransient", retryBatch);
        return retryBatch;
    }
322635
private void checkColumn(int column) throws SQLException {

        if (column < 1 || column > columnCount) {
            throw Util.sqlException(ErrorCode.JDBC_COLUMN_NOT_FOUND,
                                    String.valueOf(column));
        }
    }
417657
def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
		""""""
		i = 0
		errcode = 0
		caughte = None
		while i < self.numTries:
			i += 1
			try:	
				cursor = self.connection.cursor(cursorClass)
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				if InnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				self.lastrowid = int(cursor.lastrowid)
				cursor.close()
				return results
			except MySQLdb.OperationalError, e:
				errcode = e[0]
				# errcodes of 2006 or 2013 usually indicate a dropped connection  
				# errcode 1100 is an error with table locking
				print(e)
				self.connection.ping(True)
				caughte = e
				continue
			except:				
				traceback.print_exc()
				break
		
		sys.stderr.write("\nSQL execution error in query at %s:" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
		sys.stderr.write("\n %s." % sql)
		sys.stderr.flush()
		sys.stderr.write("\nErrorcode: '%s'.\n" % (str(caughte)))
		sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
692390
function ExecuteSql()
    {
        $versionCompare = version_compare($this->installedVersion, $this->manifest->Version());
       
        if ($versionCompare > 0)
        {
            $bundle = $this->manifest->BundleName();
            throw new \Exception("Error instaling bundle $bundle: Previously installed version is greater than curren code version. Please re-install the bundle.");
        }
        else if ($versionCompare === 0)
        {
            return;
        }
        $engineFolder = $this->FindEngineFolder();
        if (!$engineFolder)
        {
            return;
        }
        $this->ExecuteScripts($engineFolder);       
    }
1085583
public function fatalError() {
        if (function_exists('error_get_last')) {
            if ($e = error_get_last()) {
                try {
                    throw new MyException($e['message'], $e['type'], $e['file'], $e['line']);
                } catch (MyException $e) {
                    ERRORCODE($e);
                }
            }
        }
    }
54140
private function tryToRecoverFromFailedQuery($sql, $arguments, $load_mode, $return_mode)
    {
        switch ($this->link->errno) {

            // Non-transactional tables not rolled back!
            case 1196:
                return null;

            // Server gone away
            case 2006:
            case 2013:
                return $this->handleMySqlGoneAway($sql, $arguments, $load_mode, $return_mode);

            // Deadlock detection and retry
            case 1213:
                return $this->handleDeadlock();

            // Other error
            default:
                throw new QueryException($this->link->error, $this->link->errno);
        }
    }
6770
def get_exception_error():
        ''' 
        '''
        error_message = ""
        for i in range(len(inspect.trace())):
            error_line = u"""
        File:      %s - [%s]
        Function:  %s
        Statement: %s
        -""" % (inspect.trace()[i][1], inspect.trace()[i][2], inspect.trace()[i][3], inspect.trace()[i][4])
            
            error_message = "%s%s" % (error_message, error_line)    
        
        error_message = u"""Error!\n%s\n\t%s\n\t%s\n-------------------------------------------------------------------------------------------\n\n""" % (error_message,sys.exc_info()[0], sys.exc_info()[1])
        
        return error_message
405907
def handle_flush_error(cls, exception):
        """"""

        trace = exception.args[0]
        m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)

        if not m:
            raise exception

        entity = m.group('entity')
        eid = m.group('eid')

        raise AlreadyExistsError(entity=entity, eid=eid)
1343319
private function _mysql_query($query) {

        // call "mysqli_query"
        $result = mysqli_query($this->link, $query);

        // stop if there was an error
        if (!$result) throw new Exception($this->_mysql_error());

        // return the result if query was successful
        return $result;

    }
235274
def _check_query(self, query, style_cols=None):
        """"""
        try:
            self.sql_client.send(
                utils.minify_sql((
                    'EXPLAIN',
                    'SELECT',
                    '  {style_cols}{comma}',
                    '  the_geom, the_geom_webmercator',
                    'FROM ({query}) _wrap;',
                )).format(query=query,
                          comma=',' if style_cols else '',
                          style_cols=(','.join(style_cols)
                                      if style_cols else '')),
                do_post=False)
        except Exception as err:
            raise ValueError(('Layer query `{query}` and/or style column(s) '
                              '{cols} are not valid: {err}.'
                              '').format(query=query,
                                         cols=', '.join(['`{}`'.format(c)
                                                         for c in style_cols]),
                                         err=err))
954767
function onError(int $code, string $message, ?string $file = null, ?int $line = null): bool
    {
        $this->lastError = error_get_last();
        $this->currentErrorException = new ErrorException(
            $message,
            $code,
            ($code & error_reporting()) === 0,
            $file ?? __FILE__,
            $line ?? __LINE__
        );

        try {
            try {
                $this->emit(ErrorHandlerEvents::ERROR, $this->currentErrorException, $this->debug);
            } catch (\Throwable $e) {
                throw new ChainedException(
                    'Additional exception was thrown from an [error] event listener. See previous exceptions.',
                    0,
                    Exception::joinChains($this->currentErrorException, $e)
                );
            }

            // check suppression state
            if (!$this->currentErrorException->isSuppressed()) {
                throw $this->currentErrorException;
            }

            // suppressed error
            return true;
        } finally {
            $this->currentErrorException = null;
        }
    }