PHP: What is the control flow for error handling?

I am new to PHP, so I apologize if this seems silly. I searched around and could not find anything that specifically explained what I was looking for.

Ultimately, I have two goals.

  • During production, when an unexpected error occurs, show the user the "oops" page by default.
  • When the expected error occurs, handle it without losing PHP.

My mental model for handling PHP errors is quite blurry, and I cannot move forward with any certainty, and I could not find good documentation about this process.

To give some contrived examples.

  • the user makes a request, the database connection fails, the message oops is displayed.
  • the user makes a request, the script does not parse correctly, we display an oops message.
  • The user makes a request, we request a database with an update using an optimistic lock. It does not work, so we inform the user that the object has been updated.

I think that most of my confusion is related to which errors lead to the death of the script and which not (using the default handler), and when the script dies, how do we gracefully inform the user?

Also, are any of the standard php functions / objects used for exceptions? If I prefer to handle exceptions in a more C style, will I not be surprised at any point? Will this change in PHP6? If so, I will make an effort to work on the differences between using style and c exceptions, but if not, I'd rather just use style c sequentially in PHP5. This is not a problem, I am interested in a solution if I do not need it.

edit: I just realized that the content does not quite match the name. I would like to know when an error occurs, what is the logical thread for PHP? That way, I can better understand how to achieve my goals regarding error handling in PHP.

+3
source share
2 answers

most tuff-built PHPs run errors that you cannot handle in the default setting.

However, you can work around this by installing your own error handler and throwing an exception instead of an error. (PHP will, whenever possible, run the handler before handling the error internally, so you can actually throw exceptions in the usual way.)

I wrote a bunch of code that you could use for this situation in my answer: PHP: exceptions against errors?

If php cannot actually parse your file, you are screwed up pretty much, php will crash a lot in most cases when it cannot parse the file. Although you can try to write your own include function, which is an eval file, before including it, and just skip if eval failed. You should be sure that you can mainly trust files.

+3
source

Exceptions are well integrated in PHP5 . They have the same try/catch syntax as Java / C ++ exceptions. Use them for the expected error.

If you want to show the custom oops page, you can use set_exception_handler in combination with trigger_error . For more tips, consider this .

0
source

Source: https://habr.com/ru/post/1415103/


All Articles