Handle common errors like database/service connection problems and display a unified
error message.

This will not log the exception, only display information to the user.

@param ex
@return True if error was handled, false otherwise.
182602
public static boolean handleCommonError(Throwable ex, String action)
  {
    if(ex != null)
    {
      Throwable rootCause = ex;
      while(rootCause.getCause() != null)
      {
        rootCause = rootCause.getCause();
      }

      if(rootCause instanceof UniformInterfaceException)
      {
        UniformInterfaceException uniEx = (UniformInterfaceException) rootCause;
        
        if(uniEx.getResponse() != null)
        {
          if(uniEx.getResponse().getStatus() == 503)
          {
            // database connection error
            Notification n = new Notification(
                "Can't execute " + (action == null ? "" : "\"" + action + "\"" ) 
                + " action because database server is not responding.<br/>"
                + "There might be too many users using this service right now.", 
                Notification.Type.WARNING_MESSAGE);
            n.setDescription("<p><strong>Please try again later.</strong> If the error persists inform the administrator of this server.</p>"
                + "<p>Click on this message to close it.</p>"
                + "<p style=\"font-size:9pt;color:gray;\">Pinguin picture by Polar Cruises [CC BY 2.0 (http://creativecommons.org/licenses/by/2.0)], via Wikimedia Commons</p>");
            n.setIcon(PINGUIN_IMAGE);
            n.setHtmlContentAllowed(true);
            n.setDelayMsec(15000);
           
            n.show(Page.getCurrent());
            
            return true;
          }
        }
       
      }
    }
    return false;
  }
1167718
def regular_error_handling?(ex) #:nodoc:
      if @error_block 
        return true if (ex.respond_to?(:exit_code) && ex.exit_code == 0)
        @error_block.call(ex)
      else
        true
      end
    end
1293492
public function handleAndResponseException(\Exception $ex)
    {

        $response = '';
        switch (true) {
            case $ex instanceof \Illuminate\Database\Eloquent\ModelNotFoundException:
                $response = $this->respondNotFound('Record not found');
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException:
                $response = $this->respondNotFound("Not found");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException:
                $response = $this->respondForbidden("Access denied");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\BadRequestHttpException:
                $response = $this->respondBadRequest("Bad request");
                break;
            case $ex instanceof BadMethodCallException:
                $response = $this->respondBadRequest("Bad method Call");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
                $response = $this->respondForbidden("Method not found");
                break;
            case $ex instanceof \Illuminate\Database\QueryException:
                $response = $this->respondValidationError("Some thing went wrong with your query", [$ex->getMessage()]);
                break;
            case $ex instanceof \Illuminate\Http\Exceptions\HttpResponseException:
                $response = $this->respondInternalError("Something went wrong with our system", [$ex->getMessage()]);
                break;
            case $ex instanceof \Illuminate\Auth\AuthenticationException:
                $response = $this->respondUnauthorized("Unauthorized request");
                break;
            case $ex instanceof \Illuminate\Validation\ValidationException:
                $response = $this->respondValidationError("In valid request", [$ex->getMessage()]);
                break;
            case $ex instanceof NotAcceptableHttpException:
                $response = $this->respondUnauthorized("Unauthorized request");
                break;
            case $ex instanceof \Illuminate\Validation\UnauthorizedException:
                $response = $this->respondUnauthorized("Unauthorized request", [$ex->getMessage()]);
                break;
            case $ex instanceof \Exception:
                $response = $this->respondInternalError("Something went wrong with our system", [$ex->getMessage()]);
                break;
        }
        return $response;
    }
608416
private void handleExceptionThrown(Context cx, Throwable ex,
                                         StackFrame frame) {
        if (breakOnExceptions) {
            ContextData cd = frame.contextData();
            if (cd.lastProcessedException != ex) {
                interrupted(cx, frame, ex);
                cd.lastProcessedException = ex;
            }
        }
    }
276464
protected void handleAdapterInvocationError(Throwable errorCause)
        throws ActivityException {
        logger.severeException(getAdapterInvocationErrorMessage(), errorCause);
        boolean isErrorRetryable;
        int errorCode;
        if (errorCause instanceof AdapterException) {
            AdapterException adEx = (AdapterException) errorCause;
            isErrorRetryable = adEx.isRetryable();
            if (adEx.getCode() != 0) {
                errorCode = adEx.getCode();
            }
            else {
                errorCode = ServiceException.INTERNAL_ERROR;
            }
        }
        else if (errorCause instanceof ConnectionException) {
            errorCode = ((ConnectionException)errorCause).getCode();
            // if process is invoked sync style, no need to retry due to connection failure
            Process procVO = getProcessDefinition();
            if (procVO.getProcessType().equals(ProcessVisibilityConstant.SERVICE)) {
                super.setReturnCode("ERROR:");
                return;
            }
            isErrorRetryable = true;
        }
        else {
            errorCode = ServiceException.INTERNAL_ERROR;
            isErrorRetryable = false;
        }

        if (isErrorRetryable) {
            super.setReturnCode(ActivityResultCodeConstant.RESULT_RETRY);
        }

        this.handleAdapterFailure(errorCode, errorCause);
    }
1340182
private boolean isExceptionHandled(String ex) {
        try {
            JavaClass thrownEx = Repository.lookupClass(ex);
            // First look at the throws clause
            ExceptionTable et = getMethod().getExceptionTable();
            if (et != null) {
                String[] throwClauseExNames = et.getExceptionNames();
                for (String throwClauseExName : throwClauseExNames) {
                    JavaClass throwClauseEx = Repository.lookupClass(throwClauseExName);
                    if (thrownEx.instanceOf(throwClauseEx)) {
                        return true;
                    }
                }
            }
            // Next look at the try catch blocks
            CodeException[] catchExs = getCode().getExceptionTable();
            if (catchExs != null) {
                int pc = getPC();
                for (CodeException catchEx : catchExs) {
                    if ((pc >= catchEx.getStartPC()) && (pc <= catchEx.getEndPC())) {
                        int type = catchEx.getCatchType();
                        if (type != 0) {
                            String catchExName = getConstantPool().getConstantString(type, Const.CONSTANT_Class);
                            JavaClass catchException = Repository.lookupClass(catchExName);
                            if (thrownEx.instanceOf(catchException)) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
        }
        return false;
    }
624623
private EJBException mapException(Throwable ex)
    {
        EJBException ejbex;
        boolean createdEx = true;
        Exception causeEx = null;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "mapException: " + ex);

        // -----------------------------------------------------------------------
        // First, obtain the message text used to create the exception.
        //
        // If the message being mapped ends up being 'replaced', then the
        // replacement should have the same message text.
        //
        // getBaseMessage insures that the message text does NOT include the
        // name of the exception class, nor any chained exception text.
        // -----------------------------------------------------------------------
        String message = ExceptionUtil.getBaseMessage(ex);

        // -----------------------------------------------------------------------
        // Second, get the cause of the exception being mapped.
        //
        // findCause will remove any internal EJB Container exceptions from
        // the exception chain.
        //
        // Also, if the cause is not a subclass of Throwable, then it must
        // be 'wrapped' in an Exception, as EJBException does not allow
        // Throwable on any of its constructors.  However, the 'cause' on
        // throwable will still be set to the intended cause.  This will allow
        // getCause() to work as expected, even though EJBException does not
        // support Throwable.
        // -----------------------------------------------------------------------
        Throwable cause = ExceptionUtil.findCause(ex);

        if (cause != null)
        {
            if (cause instanceof Exception)
            {
                causeEx = (Exception) cause;
            }
            else
            {
                causeEx = new Exception("See nested Throwable", cause);
            }
        }

        // -----------------------------------------------------------------------
        // Next, map Throwable to an EJBException to return.
        //
        // These mappings are prescribed by the EJB & ActivitySession specs.
        //
        // Note: When adding new mappings, do NOT call 'initCause', as that
        //       will be performed below, and handles the fact that EJBException
        //       may not be created with a throwable.
        //
        // Caution: Do NOT look at the cause to perform mapping. If an exception
        //          is 'wrapped' in another exception, it likely was wrapped
        //          by another EJB method call, and a failure from a downstream
        //          method call should NOT be treated the same here.
        //          If it appears the cause needs to be examined, then instead,
        //          find the code that wrapped the cause, and stop wrapping it.
        // -----------------------------------------------------------------------
        if (ex instanceof CSIException)
        {
            ejbex = mapCSIException((CSIException) ex, causeEx, cause);
            createdEx = false;
        }
        else if (ex instanceof NoSuchObjectException)
        {
            ejbex = new NoSuchEJBException(message, causeEx);
        }
        else if (ex instanceof EJBStoppedException) // d350987
        {
            // Don't just replace the EJBStoppedException, but nest it as the
            // cause so applications may check for it.
            cause = ex;
            causeEx = (Exception) ex;
            ejbex = new NoSuchEJBException((String) null, causeEx);
        }
        else if (ex instanceof TransactionRequiredException)
        {
            ejbex = new EJBTransactionRequiredException(message); // d395666
        }
        else if (ex instanceof TransactionRolledbackException)
        {
            ejbex = new EJBTransactionRolledbackException(message, causeEx); // d395666
        }
        else if (ex instanceof InvalidTransactionException)
        {
            ejbex = new InvalidTransactionLocalException(message, causeEx);
        }
        else if (ex instanceof AccessException)
        {
            ejbex = new EJBAccessException(message); // d395666
        }
        //        else if (ex instanceof ActivityRequiredException)
//        {
//            ejbex = new ActivityRequiredLocalException(message, causeEx);
//        }
//        else if (ex instanceof InvalidActivityException)
//        {
//            ejbex = new InvalidActivityLocalException(message, causeEx);
//        }
//        else if (ex instanceof ActivityCompletedException)
//        {
//            ejbex = new ActivityCompletedLocalException(message, causeEx);
//        }
        else if (ex instanceof BeanNotReentrantException)
        {
            BeanNotReentrantException bnre = (BeanNotReentrantException) ex;
            if (bnre.isTimeout())
            {
                // EJB 3.1 has defined an exception for this purpose.      d653777.1
                ejbex = new ConcurrentAccessTimeoutException(message);
            }
            else
            {
                // EJB 3.0 has defined an exception for this purpose.      d366807.6
                ejbex = new ConcurrentAccessException(message, causeEx);
            }
        }
        else
        {
            // --------------------------------------------------------------------
            // All other exceptions are just be mapped to an EJBException.
            //
            // If the exception is an EJBException, it will just be returned
            // (with the throwable cause filled in), else the exception will
            // just be wrapped in an EJBException, with the stack and cause
            // set appropriately.
            // --------------------------------------------------------------------
            ejbex = ExceptionUtil.EJBException(ex);
            createdEx = false;
        }

        // -----------------------------------------------------------------------
        // Finally, EJBException doesn't normally set the cause on Throwable,
        // so let's do that to be nice :-) and clear the stack of the
        // EJBException, as it is mostly confusing and causes very
        // similar stacks to be printed out twice.
        //
        // Note that this code, especially clearing of the stack, is only
        // performed for EJBExceptions that were created in this method.
        // EJBExceptions that will just be propagated should NOT have the
        // stack cleared, as they were likely thrown by the customer.
        // -----------------------------------------------------------------------
        if (createdEx)
        {
            if (causeEx != null)
            {
                // Intentionally, the 'cause' is set as the 'cause', and not
                // 'causeEx'.  They will be the same, except when 'causeEx'
                // is just a silly wrapper around a Throwable.
                //
                // Geronimo EJBException.getCause returns getCausedbyException, so
                // we do not expect this code to be used.                     F53643
                if (ejbex.getCause() == null) { //F743-16279
                    // Use the 'real' cause here, not the possibly wrapped one.
                    ejbex.initCause(cause);
                }
            }
            else
            {
                ejbex.setStackTrace(ex.getStackTrace());
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "mapException returning: " + ejbex);

        return ejbex;
    }
70442
static DnsException translateAndThrow(RetryHelperException ex) {
    BaseServiceException.translate(ex);
    throw new DnsException(UNKNOWN_CODE, ex.getMessage(), ex.getCause());
  }
505048
public function onIOError(Connection $conn, \Exception $ex)
    {
        $this->onPublishResponse($conn, "IO_ERROR", $ex);

        try {
            $this->lookup->removeConnection($conn);
            $conn->tryClose();
        } catch (\Throwable $ignore) {
            sys_echo("nsq({$conn->getAddr()}) onIOError exception: {$ex->getMessage()}");
        } catch (\Exception $ignore) {
            sys_echo("nsq({$conn->getAddr()}) onIOError exception: {$ex->getMessage()}");
        }
    }
579524
public static boolean handleExceptionAndReturnFalse(Logger log,
            Throwable throwable, String method, Object... params) {
        handleException(log, throwable, method, params);
        return false;
    }
304327
private void handleRetryForStorageException(final StorageException exs) throws StorageException {
    retries++;
    if (retries > maxRetries) {
      throw new StorageException(
          exs.getCode(),
          "All "
              + maxRetries
              + " retries failed. Waited a total of "
              + totalWaitTime
              + " ms between attempts",
          exs);
    }
    sleepForAttempt(retries);
  }
426685
public void stopOnError(Exception ex) {
        this.cache.setSwapToDisk(false);
        stop(HTODDynacache.COMPLETE_CLEAR);
        close(!DELETE_IN_PROGRESS_FILE);
        Tr.error(tc, "DYNA0072E", new Object[] { this.cacheName, swapDirPath, ex.getMessage() });
    }
1198134
private boolean handleForceSectionsSQLException(SQLException sqlex) throws InterruptedException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "handleForceSectionsSQLException", new java.lang.Object[] { sqlex, this });

        boolean retryBatch = true;
        boolean failAndReport = false;
        int batchRetries = 0;

        // Set the exception that will be reported
        _nonTransientExceptionAtRuntime = sqlex;

        while (retryBatch && !failAndReport && batchRetries < _transientRetryAttempts) {
            // Should we attempt to reconnect? This method works through the set of SQL exceptions and will
            // return TRUE if we determine that a transient DB error has occurred
            retryBatch = sqlTransientErrorHandlingEnabled && isSQLErrorTransient(sqlex);
            batchRetries++;
            if (retryBatch) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Try to reexecute the SQL using connection from DS: " + _theDS + ", attempt number: " + batchRetries);
                if (_theDS != null) {
                    Connection conn = null;
                    int initialIsolation = Connection.TRANSACTION_REPEATABLE_READ;
                    // Re-execute the SQL
                    try {
                        // Get a connection to database via its datasource
                        conn = _theDS.getConnection();

                        // Take the HA DB lock and then reexecute the batch
                        initialIsolation = prepareConnectionForBatch(conn);
                        takeHADBLock(conn);
                        executeBatchStatements(conn);

                        conn.commit();
                        // The Batch has executed successfully and we can continue processing
                        retryBatch = false;
                    } catch (SQLException sqlex2) {
                        // We've caught another SQLException. Assume that we've retried the connection too soon.
                        // Make sure we inspect the latest exception
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "reset the sqlex to " + sqlex2);
                        sqlex = sqlex2;
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "sleeping for " + _transientRetrySleepTime + " millisecs");
                        Thread.sleep(_transientRetrySleepTime);
                    } catch (Throwable exc) {
                        // Not a SQLException, break out of the loop and report the exception
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "Failed got exception: " + exc);
                        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
                            if (tc.isDebugEnabled())
                                Tr.debug(tc, " " + ste);
                        }

                        failAndReport = true;
                        _nonTransientExceptionAtRuntime = exc;
                    } finally {
                        if (conn != null) {
                            if (retryBatch) {
                                // Attempt a rollback. If it fails, trace the failure but allow processing to continue
                                try {
                                    conn.rollback();
                                } catch (Throwable exc) {
                                    // Trace the exception
                                    if (tc.isDebugEnabled())
                                        Tr.debug(tc, "Rollback Failed, when handling ForceSections SQLException, got exception: " + exc);
                                }
                            }
                            // Attempt a close. If it fails, trace the failure but allow processing to continue
                            try {
                                closeConnectionAfterBatch(conn, initialIsolation);
                            } catch (Throwable exc) {
                                // Trace the exception
                                if (tc.isDebugEnabled())
                                    Tr.debug(tc, "Close Failed, when handling ForceSections SQLException, got exception: " + exc);
                            }
                        } else if (tc.isDebugEnabled())
                            Tr.debug(tc, "Connection was NULL");
                    }
                } else {
                    // This is unexpected and catastrophic, the reference to the DataSource is null
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "NULL DataSource reference");
                    failAndReport = true;
                }
            } else
                failAndReport = true;
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "handleForceSectionsSQLException", failAndReport);
        return failAndReport;
    }
1220783
private static void _invokeCustomExceptionCallback (@Nonnull final Throwable ex)
  {
    s_aExceptionCallbacks.forEach (x -> x.onException (ex));
  }
176166
@Override
    public Response toResponse(WebApplicationException ex) {
        return Response.status(ex.getResponse().getStatus()).entity(new ErrorMessage(ex.getResponse().getStatus(), ex.getMessage())).type(
            MediaType.APPLICATION_JSON_TYPE).build();
    }
1225623
public boolean isConnectionError(SQLException ex) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(this, tc, "isConnectionError", ex);

        // Maintain a set in order to check for cycles
        Set<Throwable> chain = new HashSet<Throwable>();

        boolean stale = false;
        for (Throwable t = ex; t != null && !stale && chain.add(t); t = t.getCause()) {
            SQLException sqlX = t instanceof SQLException ? (SQLException) t : null;
            if (isTraceOn && tc.isDebugEnabled())
                Tr.debug(this, tc, "checking " + t,
                         sqlX == null ? null : sqlX.getSQLState(),
                         sqlX == null ? null : sqlX.getErrorCode());
            if (sqlX != null)
                stale |= sqlX instanceof SQLRecoverableException ||
                         sqlX instanceof SQLNonTransientConnectionException ||
                         sqlX instanceof SQLTransientConnectionException && failoverOccurred(sqlX) ||
                         staleErrorCodes.contains(sqlX.getErrorCode()) ||
                         staleSQLStates.contains(sqlX.getSQLState());
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(this, tc, "isConnectionError", stale);

        return stale;
    }
408023
public function exception_handler($ex) {
        // detect active db transactions, rollback and log as error
        abort_all_db_transactions();

        // some hacks might need a cleanup hook
        $this->session_cleanup($ex);

        // now let the plugin send the exception to client
        $this->send_error($ex);

        // not much else we can do now, add some logging later
        exit(1);
    }