Error handling in PHP

后端 未结 9 1691
长情又很酷
长情又很酷 2020-12-02 08:40

I\'m familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especia

相关标签:
9条回答
  • 2020-12-02 09:16

    You should use Error Handling in cases where you don't have explicit control over the data your script is working on. I tend to use it frequently for example in places like form validation. Knowing how to spot error prone places in code takes some practice: Some common ones are after function calls that return a value, or when dealing with results from a database query. You should never assume the return from a function will be what your expecting, and you should be sure to code in anticipation. You don't have to use try/catch blocks, though they are useful. A lot of times you can get by with a simple if/else check.

    Error handling goes hand in hand with secure coding practices, as there are a lot of "errors" that don't cause your script to simply crash. while not being strictly about error handling per se, addedbytes has a good 4 article series on some of the basics of secure PHP programming which you can find HERE. There are a lot of other questions here on stackoverflow on topics such as mysql_real_escape_string and Regular Expressions which can be very powerful in confirming the content of user entered data.

    0 讨论(0)
  • 2020-12-02 09:17

    besides handling errors right away in your code you can also make use of

    http://us.php.net/manual/en/function.set-exception-handler.php
    and
    http://us.php.net/manual/en/function.set-error-handler.php

    I find setting your own exception handler particularly useful. When an exception occurs you can perform different operations depending on what type of exception it is.

    ex: when a mysql_connet call returns FALSE I throw a new DBConnectionException(mysql_error()) and handle it a "special" way: log the error, the DB connection info (host, username, password) etc and maybe even email the dev team notifying them that something may be really wrong with the DB

    I use this to compliment standard error handling. i wouldnt recommend overusing this approach

    0 讨论(0)
  • 2020-12-02 09:19

    You can also use Google Forms to catch and analyse exceptions, without having to maintain a database or publicly accessible server. There is a tutorial here that explains the process.

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