开发者

PHP: What is the flow of control for error handling?

I'm new to PHP so I apologize if this seems silly. I've searched around and couldn't find anything that explained specifically what I'm looking for.

Ultimately I have two goals.

  1. In production, when an unexpected error occurs, show the user a default "oops" page.
  2. When an expected error occurs, handle it without PHP dying.

My mental model of PHP error handling is spotty enough that I can't move forward with any confidence and I haven't been able to find any good documentation about the process.

To give some contrived examples.

  1. user makes a request, connection to the DB fails, we display an oops message.
  2. user makes a request, script doesn't parse correctly, we display an oops message.
  3. user makes a request, we query the DB with an update using optimistic locking. It fails, so we inform the user that the object has been updated.

I think most of my confusion is surrounding what errors result in the script dying and what errors do not (using the default handler), and when the script dies, how do we gracefully inform the user?

Also, do any of the standard php functions/objects use exceptions? If I choose to handle exceptions in more of a C style I'm not going to be surprised at any point am I? Is this going to change in PHP6? If so I'll put forth the effort to paper over the differences between using c style and exceptions, but if not, I'd rather just use the c style consistently throughout PHP5. That is not a problem I am interested in solving unless I absolutely need to.

edit: I just realized the content doesn't quite match the title. I woul开发者_运维技巧d like to know, when an error occurs, what is the logic flow for PHP? This way I can better understand how to go about achieving my goals with respect to error handling in PHP.


most of PHP's built in tuff triggers errors that you can't really deal with in a default setup.

You can however workaround this by setting up a custom error handler and throwing an exception instead of the error. (PHP will, when possible, run your handler before handling the error internally, so you can actually catch Exceptions in the normal way.)

I've written a bunch of code you could use for this situation in my answer here: PHP: exceptions vs errors?

If php can't actually parse your file you're pretty much screwed, php will crash pretty hard under most circumstances where it can't parse a file. Though you could try writing your own include function that eval's a file before including it and just skips if eval failed. You'll need to be sure you can basically trust the files though.


Exceptions are well integrated into PHP5. They have the same try/catch syntax as Java/C++ exceptions. Use them when an expected error occurs.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜