PHP: hataları incelikle yönetmek nasıl?

2 Cevap php

Web (API, veritabanı) üzerinde bir şey erişmek için başarısız olunca, ben nasıl senaryonun kalanını yürütme durdurmak ve günlük dosyasında hata oturum istiyorsunuz? Eh, ve ziyaretçinin kesin nedeni görmek olmaz ki ama bunun yerine (ki, 'oluverdi kötü bir şey') benim özel mesaj göreceksiniz. Ben şeyleri düzenlemek için hangi adımlar gerekiyor?

2 Cevap

Bana tek bir yerde tüm hata işleme kodu olmasını sağlar: genel durum bu tür, Exceptions kullanarak gibi.


For instance, I'd use something a bit like this :

try {
    // Some code

    // Some code that throws an exception

    // Some other code -- will not be executed when there's been an Exception

} catch (Exception $e) {
    // Log the technical error to file / database

    // Display a nice error message
}

Bunun üzerine, tüm hata işleme kodu catch bloğunda - ve benim bütün uygulama accros scatterred değil.


Note, though, that many PHP functions don't throw exceptions, and only raise a warning or an error...

For those, you could use set_error_handler to define your own error handler -- which could throw an Exception ;-)
For instance, see the example on the manual page of ErrorException.

Bu birçok hatalar / uyarılar için gerçek para cezası çalışacak olsa da, bunu Parse Error, ne Fatal Error için çalışmaz dikkat etmelisiniz:

  • PHP kodu aslında çalıştırılmadan önce ilk tür aslında yetiştirilir
  • Ve ikinci tür ... iyi ... Ölümcül vardır.


And I would never place any die nor exit in the middle of my code : that's, in my opinion, one of the worst possible way of dealing with errors.

Ben de benim sunucu / uygulama için yapılandırabilirsiniz olacaktır:

and so that the visitor wouldn't see the exact cause but rather they would see my custom message

Sana custom error handling in PHP David Walsh tarafından bu mükemmel yazı geçmesi öneririm.

Bunun için set_error_handler() işlevini kullanabilirsiniz.

how would I stop executing the rest of the script and log the error in the log file?

Hataları log PHP varsayılan bir işlevi vardır; error_log

Example from PHP.net:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
    exit; //exit
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

.

More Resources:

This is also good article covering most of it related to error handling.