source

php: try-display가 모든 예외를 포착하지 못함

factcode 2023. 1. 29. 20:17
반응형

php: try-display가 모든 예외를 포착하지 못함

다음을 수행하려고 합니다.

try {
    // just an example
    $time      = 'wrong datatype';
    $timestamp = date("Y-m-d H:i:s", $time);
} catch (Exception $e) {
    return false;
}
// database activity here

요컨대 데이터베이스에 넣을 변수를 초기화합니다.예를 들어 $time이 예상된 형식이 아니기 때문에 어떤 이유로든 초기화가 실패했을 경우 메서드는 false를 반환하고 잘못된 데이터를 데이터베이스에 입력하지 않도록 합니다.

단, 이러한 오류는 catch' 스테이트먼트가 아니라 글로벌오류 핸들러에 의해 검출됩니다.그리고 스크립트는 계속됩니다.

이 문제를 해결할 방법이 있나요?모든 변수를 수동으로 체크하는 대신 이렇게 하는 것이 더 깨끗하다고 생각했습니다. 모든 경우 99%의 경우 나쁜 일이 발생하지 않는다는 점을 고려하면 효과가 없는 것 같습니다.

try {
  // call a success/error/progress handler
} catch (\Throwable $e) { // For PHP 7
  // handle $e
} catch (\Exception $e) { // For PHP 5
  // handle $e
}

솔루션 #1

ErrorException을 사용하여 오류를 처리할 예외로 만듭니다.

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

솔루션 #2

try {
    // just an example
    $time      = 'wrong datatype';
    if (false === $timestamp = date("Y-m-d H:i:s", $time)) {
        throw new Exception('date error');
    }
} catch (Exception $e) {
    return false;
}

내가 찾은 짧은 길이:

set_error_handler(function($errno, $errstr, $errfile, $errline ){
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});

모든 오류를 포착 가능한 인스턴스로 만듭니다.ErrorException

사용할 수 있습니다.catch(Throwable $e)다음과 같은 예외 및 오류를 모두 파악합니다.

catch ( Throwable $e){
    $msg = $e->getMessage();
}

또, 복수의 타입을 정의할 수도 있습니다.$e캐치 매개 변수:

try {
    // just an example
    $time      = 'wrong datatype';
    $timestamp = date("Y-m-d H:i:s", $time);
} catch (Exception|TypeError $e) {
    return false;
}

언급URL : https://stackoverflow.com/questions/15461611/php-try-catch-not-catching-all-exceptions

반응형