PHP.mk документација

Exception::getTraceAsString

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

exception.gettraceasstring.php PHP.net прокси Преводот е вчитан
Оригинал на PHP.net
Патека exception.gettraceasstring.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + преведен приказ Кодовите, табелите и белешките остануваат читливи во истиот тек.
Exception::getTraceAsString

Референца за `exception.gettraceasstring.php` со подобрена типографија и навигација.

exception.gettraceasstring.php

Exception::getTraceAsString

класата mysqli_driver

Exception::getTraceAsStringЈа добива трагата на стекот како стринг

= NULL

final public Exception::getTraceAsString(): string

Враќа трага на стек на исклучок како стринг.

Параметри

Оваа функција нема параметри.

Вратени вредности

Враќа трага на стек на исклучок како стринг.

Примери

Пример #1 (PHP 5, PHP 7, PHP 8) example

<?php
function test() {
throw new
Exception;
}

try {
test();
} catch(
Exception $e) {
echo
$e->getTraceAsString();
}
?>

Горниот пример ќе прикаже нешто слично на:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

Види Исто така

Белешки од корисници 2 забелешки

Throwable::getTraceAsString()
пред 11 години
Honestly, Exception::getTraceAsString() simply sucks, listing only the called method (below, for example, on line 89 function fail2() gets called, but there's no information that you have the originator is fail1()). The fact that, in the example below, the exception gets thrown on line 78, is completely omitted from the trace and only available within the exception. Chained exceptions are not supported as well.

Example:
#0 /var/htdocs/websites/sbdevel/public/index.php(70): seabird\test\C->exc()
#1 /var/htdocs/websites/sbdevel/public/index.php(85): seabird\test\C->doexc()
#2 /var/htdocs/websites/sbdevel/public/index.php(89): seabird\test\fail2()
#3 /var/htdocs/websites/sbdevel/public/index.php(93): seabird\test\fail1()
#4 {main}

jTraceEx() provides a much better java-like stack trace that includes support for chained exceptions:
Exception: Thrown from class C
 at seabird.test.C.exc(index.php:78)
 at seabird.test.C.doexc(index.php:70)
 at seabird.test.fail2(index.php:85)
 at seabird.test.fail1(index.php:89)
 at (main)(index.php:93)
Caused by: Exception: Thrown from class B
 at seabird.test.B.exc(index.php:64)
 at seabird.test.C.exc(index.php:75)
 ... 4 more
Caused by: Exception: Thrown from class A
 at seabird.test.A.exc(index.php:46)
 at seabird.test.B.exc(index.php:61)
 ... 5 more

(see at the end for the example code)
 
 <?php
 /**
 * jTraceEx() - provide a Java style exception trace
 * @param $exception
 * @param $seen      - array passed to recursive calls to accumulate trace lines already seen
 *                     leave as NULL when calling this function
 * @return array of strings, one entry per trace line
 */
function jTraceEx($e, $seen=null) {
    $starter = $seen ? 'Caused by: ' : '';
    $result = array();
    if (!$seen) $seen = array();
    $trace  = $e->getTrace();
    $prev   = $e->getPrevious();
    $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage());
    $file = $e->getFile();
    $line = $e->getLine();
    while (true) {
        $current = "$file:$line";
        if (is_array($seen) && in_array($current, $seen)) {
            $result[] = sprintf(' ... %d more', count($trace)+1);
            break;
        }
        $result[] = sprintf(' at %s%s%s(%s%s%s)',
                                    count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '',
                                    count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '',
                                    count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)',
                                    $line === null ? $file : basename($file),
                                    $line === null ? '' : ':',
                                    $line === null ? '' : $line);
        if (is_array($seen))
            $seen[] = "$file:$line";
        if (!count($trace))
            break;
        $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source';
        $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null;
        array_shift($trace);
    }
    $result = join("\n", $result);
    if ($prev)
        $result  .= "\n" . jTraceEx($prev, $seen);

    return $result;
}
?>

Here's the example code:
<?php
class A {
    public function exc() {
        throw new \Exception('Thrown from class A');    // <-- line 46
    }
}

class B {
    public function exc() {
        try {
            $a = new A;
            $a->exc();    // <-- line 61
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class B', 0, $e1);    // <-- line 64
        }
    }
}
class C {
    public function doexc() {
        $this->exc();    // <-- line 70
    }
    public function exc() {
        try {
            $b = new B;
            $b->exc();    // <-- line 75
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class C', 0, $e1);    // <-- line 78
        }
    }
}

function fail2() {
    $c = new C;
    $c->doexc();    // <-- line 85
}

function fail1() {
    fail2();            // <-- line 89
}

try {
    fail1();            // <-- line 93
}
catch(\Exception $e) {
    echo jTraceEx($e);
}
?>
cottton на i-stats точка net
пред 11 години
this method uses \n for new line (i expected PHP_EOL but well ...).
if you want to log the string as one single line use something like:
<?php
$separator = ', ';
$one_line = str_replace("\n", $separator, $e->getTraceAsString());
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.