How can I reliably identify a specific error in PHP?

后端 未结 4 1835
太阳男子
太阳男子 2021-01-14 19:31

Because of PHP\'s unlink() not supporting exceptions natively, I\'m making a wrapper function for it. It should throw a FileNotFoundException if, w

相关标签:
4条回答
  • 2021-01-14 19:35

    I've seen php error messages change quite a bit over the years. Maybe, try to detect a change in the last error over a very granular piece of code, and then result to string parsing in a very loose manor.

    $lastErr = error_get_last();
    unlink($file);
    if ($lastErr !== error_get_last()) {
        // do something
        //maybe string parsing and/or testing with file_exists, is_writable etc...
    }
    
    0 讨论(0)
  • 2021-01-14 19:42

    I believe it(i.e. your code) should be portable enough as it is... As regards a better way to achieve the same thing, i would do things differently (although the code is simple, it's also more readable...so bear with me)

    function deleteFile($file_path){
        if(!is_file($file_path)){
            throw new Exception("The path does not seem to point to a valid file");
        }
        if(!file_exists($file_path)){
            throw new Exception("File not found!");
        }
        if(unlink($file_path)){
            return true;
        } else {
            throw new Exception("File deletion failed!");
        }
    }
    

    Of course you can always compress and improve on the code...hop this helps!

    0 讨论(0)
  • 2021-01-14 19:46

    I would simplify the code:

    public function deleteFile($path){
    
        if (!file_exists($path) {
            throw new FileNotFoundException();
        }else{
            unlink($path);
        }
    
        if (file_exists($path) {
            throw new FileNotDeleted();
        }
    }
    

    Then you don't have to catch the $errstr and do complicated error catching. And it will work down to PHP 4 when exceptions were introduced.

    0 讨论(0)
  • 2021-01-14 19:59

    While reading trough my old questions I came across the ErrorException, combined with set_error_handler() this would be a automatic Error to Exception transformer for all native PHP errors:

    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
    set_error_handler("exception_error_handler");
    
    /* Trigger exception */
    unlink('Does not exitsts'); 
    

    Can anybody prof this?

    0 讨论(0)
提交回复
热议问题