php bilinmeyen bir özel durum hata

2 Cevap

i bir komut atılan tüm özel durumları yakalamak istiyorum ve onlar bir hata kodu 23000 varsa o kontrol edin.

onlar yoksa ben istisna rethrow istiyorum.

İşte benim kod:

function myException($exception) {
    /*** If it is a Doctrine Connection Mysql Duplication Exception ***/
    if(get_class($exception) === 'Doctrine_Connection_Mysql_Exception' && $exception->getCode() === 23000) {
         echo "Duplicate entry";
    } else {
         throw $exception;
    }
}

set_exception_handler('myException');

$contact = new Contact();
$contact->email = 'peter';
$contact->save();

ama bu hata mesajı alıyorum ve ben bunun ne anlama geldiğini bilmiyorum:

Fatal error: Exception thrown without a stack frame in Unknown on line 0

i hata kodu 23000 değil varsa orijinal hata iletisini rethrow edebilmek istiyorum.

i çek errorCode silinmiş olsa bile ben yine aynı mesajı alıyorum:

function myException($exception) {
    throw $exception;
}

set_exception_handler('myException');

$contact = new Contact();
$contact->email = 'peter';
$contact->save();

Bu nasıl çözebilir?

teşekkürler

2 Cevap

Bunun için istisna işleyici kullanmayın.

Durum işleyicisi uncaught istisnaları işlemek için sadece "son çare" dir.

Bunu içinde yeni bir istisna değil - bu sonsuz bir döngüye yol açacak.

Istisnaları işlemek için düzenli bir şekilde bir try... catch {} bloğu kullanıyor:

try
 {
  $contact->save();
 }
catch (Exception $exception)
 {
  if(get_class($exception) === 'Doctrine_Connection_Mysql_Exception' 
     && $exception->getCode() === 23000) {
         echo "Duplicate entry";
    } else {
         throw $exception; // throw it on if it's not a doctrine exception
                           // (if that's what you want)
    }

 }

Ben bu şekilde daha dağınık bunu yol daha görünüyor biliyor. Ben istisnalar gerçekten düşkün değilim bu yüzden.

Emin değilim ama bu kodu deneyin

function myException($exception) {
    restore_exception_handler();
    throw $exception;
}
//you can set here another exception handler that will be restored.
//or your exception will be thrown to standard handler
//set_exception_handler('myException2');

set_exception_handler('myException');

$contact = new Contact();
$contact->email = 'peter';
$contact->save();