Wrapper that converts PHP errors to exceptions and passes them
to the standard error50x handler.
12684
public function php_error_handler($errno, $errstr, $errfile, $errline)
    {
        $e = new \Exception($errstr, $errno);
        call_user_func($this->error50x, $e);
    }
807267
public function convertErrorsToExceptions($level = null, $exceptionClass = null)
    {
        $this->isHandledLocal = true;
        if (is_null($level)) {
            $level = E_ALL;
        }
        if (is_null($exceptionClass)) {
            $exceptionClass = static::EXCEPTION_THROW_CLASS;
        }
        set_error_handler(function ($errorNumber, $errorMessage, $errorFile, $errorLine) use ($exceptionClass) {
            throw new $exceptionClass(
                sprintf("%s in %s on line %s!", $errorMessage, $errorFile, $errorLine),
                $errorNumber
            );
        }, $level);
    }
727656
public static function handleFatalError(array $error = null)
    {
        if (null === self::$reservedMemory) {
            return;
        }

        $handler = self::$reservedMemory = null;
        $handlers = [];
        $previousHandler = null;
        $sameHandlerLimit = 10;

        while (!\is_array($handler) || !$handler[0] instanceof self) {
            $handler = set_exception_handler('var_dump');
            restore_exception_handler();

            if (!$handler) {
                break;
            }
            restore_exception_handler();

            if ($handler !== $previousHandler) {
                array_unshift($handlers, $handler);
                $previousHandler = $handler;
            } elseif (0 === --$sameHandlerLimit) {
                $handler = null;
                break;
            }
        }
        foreach ($handlers as $h) {
            set_exception_handler($h);
        }
        if (!$handler) {
            return;
        }
        if ($handler !== $h) {
            $handler[0]->setExceptionHandler($h);
        }
        $handler = $handler[0];
        $handlers = [];

        if ($exit = null === $error) {
            $error = error_get_last();
        }

        if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
            // Let's not throw anymore but keep logging
            $handler->throwAt(0, true);
            $trace = isset($error['backtrace']) ? $error['backtrace'] : null;

            if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
                $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
            } else {
                $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
            }
        } else {
            $exception = null;
        }

        try {
            if (null !== $exception) {
                self::$exitCode = 255;
                $handler->handleException($exception, $error);
            }
        } catch (FatalErrorException $e) {
            // Ignore this re-throw
        }

        if ($exit && self::$exitCode) {
            $exitCode = self::$exitCode;
            register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
        }
    }
1223560
def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
        

        def decorator(callback):
            self.register_errors_handler(self._wrap_async_task(callback, run_task),
                                         *custom_filters, exception=exception, **kwargs)
            return callback

        return decorator
97827
def convert_error(exc_src, exc_dest):
    

    def wrap(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except exc_dest:
                raise
            except exc_src as err:
                reraise(exc_dest, err, sys.exc_info()[2])

        return wrapper

    return wrap
71597
public static function errorHandler($code, $message, $file, $line)
    {
        // Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
        $enabled = (bool) ($code & ini_get('error_reporting'));

        // -- FATAL ERROR
        // throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
        if (in_array($code, array(E_USER_ERROR, E_RECOVERABLE_ERROR, E_WARNING)) && $enabled) {
            throw new ErrorException($message, 0, $code, $file, $line);
        }

        // -- NON-FATAL ERROR/WARNING/NOTICE
        // Log the error if it's enabled, otherwise just ignore it
        else {
            if ($enabled) {
                error_log($message, 0);
                return false; // Make sure this ends up in $php_errormsg, if appropriate
            }
        }
    }
1277688
def exception_handler(exceptionObj):
    """"""
    try:
        if isinstance(exceptionObj, Exception) and hasattr(exceptionObj, 'args'):
            if not (hasattr(exceptionObj, 'message' or hasattr(exceptionObj, 'msg'))):
                if len(exceptionObj.args) >= 1:
                    if type(exceptionObj.args[0]) == type(b''):
                        ob = json.loads(exceptionObj.args[0].decode('utf-8'))
                        if type(ob) == type({}) and ob['message']:
                            return ob['message']
                    else:

                        try:
                            if type(exceptionObj.args[0]) == type('') and exceptionObj.args[0][0] == 'b':
                                ob = json.loads(exceptionObj.args[0][2:-1])
                            else:
                                ob = json.loads(exceptionObj.args[0])
                            if type(ob) == type({}) and ob['message']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['message']
                            elif type(ob) == type({}) and ob['msg']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['msg']
                            return str(json.loads(exceptionObj.args[0]))
                        except Exception as e:
                            return str(exceptionObj.args[0])
            elif hasattr(exceptionObj, 'msg'):
                return exceptionObj.msg
            elif hasattr(exceptionObj, 'message'):
                return exceptionObj.message
        elif type(exceptionObj) == type(''):
            try:
                ob = json.loads(exceptionObj)
                if type(ob) == type({}):
                    if ob['message']:
                        return ob['message']
                    elif ob['msg']:
                        return ob['msg']
                    else:
                        return ob
            except Exception as e:
                return exceptionObj

    except Exception as e:
        return e
932094
def print_errors(function):
    """"""

    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except BaseException as e:
            print ("Exception raise calling %s: %s"
                   % (reflect.canonical_name(function),
                      get_exception_message(e)))
            raise

    return wrapper
1033660
static function errorHandler($errno, $errstr, $errfile, $errline) {
	    switch ($errno) {
	    case E_USER_ERROR:
	        echo "<b>ERROR:</b> [$errno] $errstr<br>
	        <b>File: </b>$errfile [$errline]<br>
	        Aborting...<br>";
	        exit(1);
	        break;

	    case E_USER_WARNING:
	        echo "<b>WARNING:</b> [$errno] $errstr<br><b>File:</b> $errfile [$errline]";
	        break;

	    case E_USER_NOTICE:
	        echo "<b>NOTICE:</b> [$errno] $errstr<br><b>File:</b> $errfile [$errline]";
	        break;

	    default:
	        echo "<b>Unknown error type:</b> [$errno] $errstr<br><b>File:</b> $errfile [$errline]";
	        break;
	    }

	    /* Don't execute PHP internal error handler */
	    return true;
	}
999418
private function createErrorHandler()
    {
        /*
         * @param int $severity
         * @param string $message
         * @param string $file
         * @param int $line
         * @return void
         * @throws ErrorException if error is not within the error_reporting mask.
         */
        return function (int $severity, string $message, string $file, int $line): void {
            if (error_reporting() & $severity) {
                throw new ErrorException($message, 0, $severity, $file, $line);
            }
        };
    }
441377
def handle_api_exceptions(
    ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
    """"""
    # flake8: ignore=C901
    # Use stderr for messages if the output is something else (e.g.  # JSON)
    use_stderr = opts.output != "pretty"

    try:
        yield
    except ApiException as exc:
        if nl:
            click.echo(err=use_stderr)
            click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
        else:
            click.secho("ERROR", fg="red", err=use_stderr)

        context_msg = context_msg or "Failed to perform operation!"
        click.secho(
            "%(context)s (status: %(code)s - %(code_text)s)"
            % {
                "context": context_msg,
                "code": exc.status,
                "code_text": exc.status_description,
            },
            fg="red",
            err=use_stderr,
        )

        detail, fields = get_details(exc)
        if detail or fields:
            click.echo(err=use_stderr)

            if detail:
                click.secho(
                    "Detail: %(detail)s"
                    % {"detail": click.style(detail, fg="red", bold=False)},
                    bold=True,
                    err=use_stderr,
                )

            if fields:
                for k, v in six.iteritems(fields):
                    field = "%s Field" % k.capitalize()
                    click.secho(
                        "%(field)s: %(message)s"
                        % {
                            "field": click.style(field, bold=True),
                            "message": click.style(v, fg="red"),
                        },
                        err=use_stderr,
                    )

        hint = get_error_hint(ctx, opts, exc)
        if hint:
            click.echo(
                "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
                err=use_stderr,
            )

        if opts.verbose and not opts.debug:
            if exc.headers:
                click.echo(err=use_stderr)
                click.echo("Headers in Reply:", err=use_stderr)
                for k, v in six.iteritems(exc.headers):
                    click.echo(
                        "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
                    )

        if reraise_on_error:
            six.reraise(*sys.exc_info())

        if exit_on_error:
            ctx.exit(exc.status or 1)
740676
public static function php_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
        if($errno & error_reporting()) {
            foreach(self::$error_handling_instances as list($logger, $level, $with_line, $with_trace)) {
                if(!($errno & $level)) {
                    continue;
                }

                switch($errno) {
                    case E_PARSE:
                        $severity = Message::ALERT;
                        break;
                    case E_CORE_ERROR:
                    case E_COMPILE_ERROR:
                        $severity = Message::CRITICAL;
                        break;
                    case E_ERROR:
                    case E_USER_ERROR:
                    case E_RECOVERABLE_ERROR:
                        $severity = Message::ERROR;
                        break;
                    case E_WARNING:
                    case E_CORE_WARNING:
                    case E_COMPILE_WARNING:
                    case E_USER_WARNING:
                        $severity = Message::WARNING;
                        break;
                    case E_NOTICE:
                    case E_USER_NOTICE:
                        $severity = Message::NOTICE;
                        break;
                    case E_DEPRECATED:
                    case E_USER_DEPRECATED:
                        $severity = Message::INFO;
                        break;
                    case E_STRICT:
                    default:
                        $severity = Message::DEBUG;
                        break;
                }

                $message = self::errnoToString($errno).": $errstr";

                if($with_line) {
                    $message = "$message in $errfile on line: $errline";
                }

                if($with_trace) {
                    throw new Exception("Not implemented yet.");
                }

                $logger->logMessage(new Message($message, $severity));
            }
        }

        return TRUE;
    }
759355
function exceptionHandler($Exception)
    {
    
        $this->inExceptionHandler = true;
    
        header('HTTP/1.1 500 Internal Server Error');
    
        try {
            $this->fb($Exception);
        } catch (Exception $e) {
            echo 'We had an exception: ' . $e;
        }
        $this->inExceptionHandler = false;
    }
723934
public function errorHandler($code, $message, $file = '', $line = '')
    {
        if ($this->error_to_exception) {

            if (ob_get_length() > 0) {
                ob_end_clean(); // Fix templates
            }

            throw new Exception($message);
        }

        $error = array(
            'code' => $code,
            'file' => $file,
            'line' => $line,
            'message' => $message,
            'backtrace' => $this->log_backtrace ? gplcart_backtrace() : array()
        );

        $print = $this->print_error || !$this->isDb();

        if (in_array($code, $this->getFatalErrorTypes())) {

            if ($print) {
                return false; // Let it fall through to the standard PHP error handler
            }

            $this->log('php_shutdown', $error, 'danger', false);
            return true;
        }

        $key = md5(json_encode($error));

        if (isset($this->errors[$key])) {
            return true;
        }

        $this->errors[$key] = $error;

        if ($print) {
            echo $this->getFormattedError($error);
        }

        $this->log('php_error', $error, 'warning', false);
        return true;
    }
245931
private function setup_exception_handler() {
		// Setup our classes default exception handler, in case anything escapes our other catches
		set_exception_handler( array( $this, 'generic_exception_handler' ) );

		// Register an error handler through our Router's catcher
		$this->response->onError( function( $response, $error_message, $error_type, $exception ) {

			// Check if we have a callable handler in our controller
			$callable = $this->get_controller_callable( 'exception_handler' );

			// Did we actually get a callable?
			if ( $callable !== false ) {
				// Call the found handler
				return call_user_func_array(
					$callable, // The array of the callable
					array( $error_message, $error_type, $exception ) // Arguments
				);
			}
			// We didn't get a callable
			else {
				// Pass the exception to our Paulus-defined exception handler
				$this->generic_exception_handler( $exception );
			}
		});
	}
301019
public static function installMinimalError2ExceptionHandler() {
    /** @noinspection PhpUnusedParameterInspection */
    set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) {
      $msg = "$errstr in $errfile line $errline";
      throw new \RuntimeException($msg, $errno);
    });
  }
536931
public function error($exception)
    {
        $response = new Response();

        // Set the default error response
        $response->setContent('There has been a problem serving this request.');
        $response->headers->set('content-type', 'text/html');
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);

        // Execute the user defined error callback
        if (is_callable($this->error)) {
            $response = call_user_func($this->error, $response, $exception);
        }

        // Send the response
        $response->send();
    }