Given a database exception determine how to fail

    Attempt to lookup a known error & abort on a meaningful
    error. Otherwise issue a generic DatabaseUnavailable exception.

    :param exc: psycopg2 exception
488306
def handle_exc(exc):
    

    err = ERRORS_TABLE.get(exc.pgcode)

    if err:
        abort(exceptions.InvalidQueryParams(**{
            'detail': err,
            'parameter': 'filter',
        }))

    abort(exceptions.DatabaseUnavailable)
11035
def _handle_exception(self, exc):
        
        exc_info = sys.exc_info()
        self.logger.exception(
            '%s while processing message #%s',
            exc.__class__.__name__, self._message.delivery_tag,
            exc_info=exc_info)
        self._measurement.set_tag('exception', exc.__class__.__name__)
        if hasattr(exc, 'metric') and exc.metric:
            self._measurement.set_tag('error', exc.metric)
        self._process.send_exception_to_sentry(exc_info)
        self._maybe_clear_confirmation_futures()
        if not self._finished:
            self.on_finish(exc)
        self._finished = True
1152030
void internalPropagateException(Throwable ex) {
    CountedCompleter<?> a = this, s = a;
    while (a.onExceptionalCompletion(ex, s) && (a = (s = a).completer) != null && a.status >= 0
        && a.recordExceptionalCompletion(ex) == EXCEPTIONAL);
  }
1297856
private Object handleFailOver(SQLException qe, Method method, Object[] args, Protocol protocol)
      throws Throwable {
    HostAddress failHostAddress = null;
    boolean failIsMaster = true;
    if (protocol != null) {
      failHostAddress = protocol.getHostAddress();
      failIsMaster = protocol.isMasterConnection();
    }

    HandleErrorResult handleErrorResult = listener.handleFailover(qe, method, args, protocol);
    if (handleErrorResult.mustThrowError) {
      listener
          .throwFailoverMessage(failHostAddress, failIsMaster, qe, handleErrorResult.isReconnected);
    }
    return handleErrorResult.resultObject;
  }
753991
def handle_exception(self, message, exc):
        # type: (Text, Exception) -> Any
        
        return self.handle_invalid_value(
            message     = message,
            exc_info    = True,
            context     = getattr(exc, 'context', {}),
        )
1182022
private void firstBlockDbFailureAnalysis(Exception e)
    {
        if (Helpers.testDbFailure(e))
        {
            jqmlogger.error("connection to database lost - loader " + this.ji.getId() + " will be restarted later");
            jqmlogger.trace("connection error was:", e);
            this.engine.loaderRestartNeeded(this);
            if (this.engine.getHandler() != null)
            {
                this.engine.getHandler().onJobInstanceDone(this.ji);
            }
            return;
        }
        else
        {
            jqmlogger.error("a database related operation has failed and cannot be recovered", e);
            resultStatus = State.CRASHED;
            endOfRun();
            return;
        }
    }
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;
    }
202688
def raise_exception(self, node, exc=None, msg='', expr=None,
                        lineno=None):
        """"""
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg
        err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
        self._interrupt = ast.Break()
        self.error.append(err)
        if self.error_msg is None:
            self.error_msg = "at expr='%s'" % (self.expr)
        elif len(msg) > 0:
            self.error_msg = msg
        if exc is None:
            try:
                exc = self.error[0].exc
            except:
                exc = RuntimeError
        raise exc(self.error_msg)
1267523
def _step_failure(self, exc):
        
        self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
        self.step_index += 1
        self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError)
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());
    }
897429
def _is_connreset(self, exc: BaseException) -> bool:
        
        return (
            isinstance(exc, (socket.error, IOError))
            and errno_from_exception(exc) in _ERRNO_CONNRESET
        )
920640
public static void checkConnectionException(SQLException exception,
      MariaDbConnection connection) {
    if (exception.getSQLState() != null) {
      SqlStates state = SqlStates.fromString(exception.getSQLState());
      if (SqlStates.CONNECTION_EXCEPTION.equals(state)) {
        connection.setHostFailed();
        if (connection.pooledConnection != null) {
          connection.pooledConnection.fireConnectionErrorOccured(exception);
        }
      }
    }
  }
661434
public void processFailure(QueryBatchException queryBatch) {
    boolean isHostUnavailableException = processException(queryBatch.getBatcher(), queryBatch, queryBatch.getClient().getHost());
    if ( isHostUnavailableException == true ) {
      try {
        logger.warn("Retrying failed batch: {}, results so far: {}, forest: {}, forestBatch: {}, forest results so far: {}",
          queryBatch.getJobBatchNumber(), queryBatch.getJobResultsSoFar(), queryBatch.getForest().getForestName(),
          queryBatch.getForestBatchNumber(), queryBatch.getForestResultsSoFar());
        queryBatch.getBatcher().retryWithFailureListeners(queryBatch);
      } catch (RuntimeException e) {
        logger.error("Exception during retry", e);
        processFailure(new QueryBatchException(queryBatch, e));
      }
    }
  }
1124581
private void fireConnectionError(SQLException e) {
    Code code = Code.UNKNOWN;
    if (e instanceof CloudSpannerSQLException) {
      code = ((CloudSpannerSQLException) e).getCode();
    }
    if (!isFatalState(code)) {
      return;
    }
    fireConnectionFatalError(e);
  }
1023488
def handle_err(self, exc):
        '''
        '''
        if self.reset_rx_on_error and isinstance(exc[1], (RxSyncError, EightbTenbError)):
            self.fifo_readout.print_readout_status()
            self.fifo_readout.reset_rx()
        else:
            # print just the first error massage
            if not self.abort_run.is_set():
                self.abort(msg=exc[1].__class__.__name__ + ": " + str(exc[1]))
            self.err_queue.put(exc)
1069181
def handleException(exception):
    
    serverException = exception
    if not isinstance(exception, exceptions.BaseServerException):
        with app.test_request_context():
            app.log_exception(exception)
        serverException = exceptions.getServerError(exception)
    error = serverException.toProtocolElement()
    # If the exception is being viewed by a web browser, we can render a nicer
    # view.
    if flask.request and 'Accept' in flask.request.headers and \
            flask.request.headers['Accept'].find('text/html') != -1:
        message = "<h1>Error {}</h1><pre>{}</pre>".format(
                    serverException.httpStatus,
                    protocol.toJson(error))
        if serverException.httpStatus == 401 \
                or serverException.httpStatus == 403:
            message += "Please try <a href=\"/login\">logging in</a>."
        return message
    else:
        responseStr = protocol.toJson(error)
        return getFlaskResponse(responseStr, serverException.httpStatus)
311625
def remote_exception(exc, tb):
    
    if type(exc) in exceptions:
        typ = exceptions[type(exc)]
        return typ(exc, tb)
    else:
        try:
            typ = type(exc.__class__.__name__,
                       (RemoteException, type(exc)),
                       {'exception_type': type(exc)})
            exceptions[type(exc)] = typ
            return typ(exc, tb)
        except TypeError:
            return exc