In some places we catch coding_exception because if a bug happens, it
would be fatal for the course page GUI; instead we just show a developer
debug message.

@param \coding_exception $e Exception that occurred
545952
protected function warn_about_invalid_availability(\coding_exception $e) {
        $name = $this->get_thing_name();
        // If it occurs while building modinfo based on somebody calling $cm->name,
        // we can't get $cm->name, and this line will cause a warning.
        $htmlname = @$this->format_info($name, $this->course);
        if ($htmlname === '') {
            // So instead use the numbers (cmid) from the tag.
            $htmlname = preg_replace('~[^0-9]~', '', $name);
        }
        $info = 'Error processing availability data for &lsquo;' . $htmlname
                 . '&rsquo;: ' . s($e->a);
        debugging($info, DEBUG_DEVELOPER);
    }
685902
public function proceed() {
        global $CFG, $USER;

        if (!$this->prepared) {
            throw new coding_exception('The course has not been prepared.');
        } else if ($this->has_errors()) {
            throw new moodle_exception('Cannot proceed, errors were detected.');
        } else if ($this->processstarted) {
            throw new coding_exception('The process has already been started.');
        }
        $this->processstarted = true;

        if ($this->do === self::DO_DELETE) {
            if ($this->delete()) {
                $this->status('coursedeleted', new lang_string('coursedeleted', 'tool_uploadcourse'));
            } else {
                $this->error('errorwhiledeletingcourse', new lang_string('errorwhiledeletingcourse', 'tool_uploadcourse'));
            }
            return true;
        } else if ($this->do === self::DO_CREATE) {
            $course = create_course((object) $this->data);
            $this->id = $course->id;
            $this->status('coursecreated', new lang_string('coursecreated', 'tool_uploadcourse'));
        } else if ($this->do === self::DO_UPDATE) {
            $course = (object) $this->data;
            update_course($course);
            $this->id = $course->id;
            $this->status('courseupdated', new lang_string('courseupdated', 'tool_uploadcourse'));
        } else {
            // Strangely the outcome has not been defined, or is unknown!
            throw new coding_exception('Unknown outcome!');
        }

        // Restore a course.
        if (!empty($this->restoredata)) {
            $rc = new restore_controller($this->restoredata, $course->id, backup::INTERACTIVE_NO,
                backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);

            // Check if the format conversion must happen first.
            if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
                $rc->convert();
            }
            if ($rc->execute_precheck()) {
                $rc->execute_plan();
                $this->status('courserestored', new lang_string('courserestored', 'tool_uploadcourse'));
            } else {
                $this->error('errorwhilerestoringcourse', new lang_string('errorwhilerestoringthecourse', 'tool_uploadcourse'));
            }
            $rc->destroy();
        }

        // Proceed with enrolment data.
        $this->process_enrolment_data($course);

        // Reset the course.
        if ($this->importoptions['reset'] || $this->options['reset']) {
            if ($this->do === self::DO_UPDATE && $this->can_reset()) {
                $this->reset($course);
                $this->status('coursereset', new lang_string('coursereset', 'tool_uploadcourse'));
            }
        }

        // Mark context as dirty.
        $context = context_course::instance($course->id);
        $context->mark_dirty();
    }
815951
public function report(Exception $e)
    {
        if ($this->shouldReport($e)) {
            $class = addslashes(get_class($e));
            $message = addslashes($e->getMessage());
            $file = addslashes($e->getFile());
            $line = addslashes($e->getLine());
            $time = date('c');
            // log locally
            $log = sprintf("[%s] [%s] %s thrown in %s on line %d\n", $time, $class, $message, $file, $line);
            error_log($log, 3, $this->di->logPath() . DIRECTORY_SEPARATOR . '/pails.error.log');
            // log to system
            $syslog = sprintf('[%s] %s thrown in %s on line %d', $class, $message, $file, $line);
            error_log($syslog);
        }
    }
340649
public function handleException($e)
    {
        if (!$e instanceof Exception) { // Since PHP 7, in addition to an Exception, an internal Error may occur.
            // Convert the Error to ErrorException
            $e = new ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); // @codeCoverageIgnore
        } // @codeCoverageIgnore

        $this->getExceptionHandler()->handle($e);
    }
857724
public function report(Exception $e)
    {
        if ($this->shouldntReport($e)) {
            return;
        }

        try {
            if ($this->plugin->bound('bugsnag.multi')) {
                $logger = $this->plugin->make('bugsnag.multi');
            } else {            
                $logger = $this->plugin->make('Psr\Log\LoggerInterface');
            }
            $logger->error($e);

        } catch (Exception $ex) {
            throw $e; // throw the original exception
        } finally {
            $this->renderException($e);
        }
    }
295903
public function hasExceptionOfCode($code)
    {
        $code = (int) $code;
        foreach ($this->_exceptions as $e) {
            if ($code == $e->getCode()) {
                return true;
            }
        }

        return false;
    }
814512
protected function handleError(Exception $e)
    {
        if($this->isCli){
            $errorCode = $e->getCode();
            exit((empty($errorCode)) ? 1 : $errorCode);	//exit the program with an error
        }
        else {
            throw new Exception($e->getMessage());
        }
    }
533909
public function error($msg, Exception $e = null) {
		if($e !== null) {
			$msg .= PHP_EOL . get_class($e) . ': (' . $e->getCode() . ') "' . $e->getMessage() . '"' . PHP_EOL;
			$msg .= 'thrown in file: ' . $e->getFile() . ' (Line: ' . $e->getLine() . ')' . PHP_EOL . PHP_EOL;
			$msg .= $e->getTraceAsString();
		}

		$msg .= PHP_EOL . PHP_EOL . '$_SERVER = ' . print_r($_SERVER, true);
		$msg .= PHP_EOL . PHP_EOL . '$_GET = ' . print_r($_GET, true);
		$msg .= PHP_EOL . PHP_EOL . '$_POST = ' . print_r($_POST, true);
		$msg .= PHP_EOL . PHP_EOL . '$_FILES = ' . print_r($_FILES, true);
		$msg .= PHP_EOL . PHP_EOL . '$_COOKIE = ' . print_r($_COOKIE, true);

		$this->mailMessage(self::LEVEL_ERROR, $msg);

		if($this->checkLevel($this->loglevels, self::LEVEL_ERROR) !== true)
			return;

		$this->writeMessage(self::LEVEL_ERROR, $msg);
	}
71413
public function exception(\Exception $e): void
    {
        $this->log(
            configDefault('exception', 'log', 'exception') ?: 'exception',
            dump($_REQUEST, 'REQUEST', true) . PHP_EOL . var_export($e, true)
        );
    }
643827
static function exceptionHandler($e) {
	    if(get_class($e) == 'PDOException'){
	        $err = $e->getMessage().'<br>code: '.$e->getCode();
	    } else {
	        $err = 
	        '<b>Code:</b>'.$e->getCode().'<br>'.
	        '<b>Message:</b> <i>'.$e->getMessage().'</i><br>'.
	        '<b>Thrown in: </b>'.$e->getFile().' ['.$e->getLine().']<br>'.
	        '<b>Stack trace:</b><pre>'.$e->getTraceAsString().'</pre>';
	        
	    }
	    exit($err);
	}
1001099
public function addException($e)
    {
        if ($e instanceof \Exception) {
            try {
                $this->bar->getCollector('exceptions')->addException($e);
            } catch (\Exception $ie) {
            } // mute exceptions there
        }
    }
1321105
public function handleException($e)
    {
        if (!$e instanceof Exception) {
            $e = new FatalThrowableError($e);
        }

        $this->getExceptionRenderer()->render($e, $this->debug());
    }
1119295
public function handle(\Exception $e) {

		try {
			ob_clean();
			$this->createResponse($e)->send();
		}
		
		catch(\Exception $e) {
			printf('Exception thrown when handling exception (%s: %s)', get_class($e), $e->getMessage());
			exit();
		}

	}
1047008
protected function error(\Exception $e)
    {
        $str  = sprintf("Message: %s\r\n", $e->getMessage());
        $str .= sprintf("Code: %s\r\n", $e->getCode());
        $str .= sprintf("File: %s (line: %s)\r\n", $e->getFile(), $e->getLine());
        $str .= sprintf("Trade: %s\r\n", $e->getTraceAsString());

        if ($this->log instanceof \Closure)
        {
            $log = $this->log;
            $log($str);
        }
    }
1373995
public function getExceptionByCode($code)
    {
        $code       = (int) $code;
        $exceptions = array();
        foreach ($this->_exceptions as $e) {
            if ($code == $e->getCode()) {
                $exceptions[] = $e;
            }
        }

        if (empty($exceptions)) {
            $exceptions = false;
        }

        return $exceptions;
    }
1078313
public function exceptionHandler($e) : void
    {
        $this->setError(
            (int) $e->getCode(),
            (string) $e->getMessage(),
            (string) $e->getFile(),
            (int) $e->getLine(),
            (string) get_class($e),
            $e->getTrace()
        );

        View::render('500.php', (object) $this->errors);
    }
600514
public function renderException(\Exception $e, OutputInterface $output)
    {
        $output->writeln('', OutputInterface::VERBOSITY_QUIET);

        do {
            $title = sprintf(
                '  [%s%s]  ',
                get_class($e),
                $output->isVerbose() && 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''
            );

            $len = Helper::strlen($title);

            $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
            // HHVM only accepts 32 bits integer in str_split, even when PHP_INT_MAX is a 64 bit integer: https://github.com/facebook/hhvm/issues/1327
            if (defined('HHVM_VERSION') && $width > 1 << 31) {
                $width = 1 << 31;
            }
            $lines = array();
            foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
                foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
                    // pre-format lines to get the right string length
                    $lineLength = Helper::strlen($line) + 4;
                    $lines[] = array($line, $lineLength);

                    $len = max($lineLength, $len);
                }
            }

            $messages = array();
            $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
            $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
            foreach ($lines as $line) {
                $messages[] = sprintf('<error>  %s  %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
            }
            $messages[] = $emptyLine;
            $messages[] = '';

            $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);

            if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
                $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);

                // exception related properties
                $trace = $e->getTrace();
                array_unshift($trace, array(
                    'function' => '',
                    'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
                    'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
                    'args' => array(),
                ));

                for ($i = 0, $count = count($trace); $i < $count; ++$i) {
                    $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
                    $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
                    $function = $trace[$i]['function'];
                    $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
                    $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';

                    $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
                }

                $output->writeln('', OutputInterface::VERBOSITY_QUIET);
            }
        } while ($e = $e->getPrevious());

        if (null !== $this->runningCommand) {
            $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
            $output->writeln('', OutputInterface::VERBOSITY_QUIET);
        }
    }