trigger_error vs. throwing exceptions

前端 未结 3 1895
臣服心动
臣服心动 2020-12-30 05:33

A similar question was asked here, but as the answers didn\'t answer my question, I\'m asking:

I\'ve almost never used trigger_error, always thrown exce

相关标签:
3条回答
  • 2020-12-30 05:40

    They both have their uses. Generally, I gear trigger_error() toward developers, since in most production environments error reporting is turned off; then, since most application errors would likely be from bad user input or undesired results based upon user input/actions, I throw exceptions to keep better control over the application (handling those exceptions in a way that both allows the app to recover, and (if necessary) informs the user about what happened in a logical way.

    Edit: that example was based off of web apps; the same could be said of any piece of variable data in a non-user-controlled application.

    0 讨论(0)
  • 2020-12-30 05:48

    I agree with your distinction, as to when to throw and when to trigger. For me, trigger_error is also something you want to make a note off, but it's not important to the current request. E.g. for debugging purposes.

    Since all my PHP errors (note: not exceptions, but warnings, notices, fatals, etc.) are logged in production, I think trigger_error is a convenient way to get stuff into said log.

    Here is an example:

    I'm using a HTTP client to access an API we integrate. Of course the library I use is object-oriented PHP and therefor makes heavy use of exceptions. I'm doing various things here and I hope this example makes sense:

    1. The HTTP client library throws an exception when the actual request failed -- e.g. due to a connection issue, such as a timeout, etc.. Of course I catch this error, but I don't elevate it to the user. My wrapper returns false and this equals to, "Temporary issue." in the frontend.
    2. In my catch() block I use trigger_error() to log debug information about the actual connection error. Since I got error_log = syslog in my php.ini all this information is send to syslog and eventually to my log master.
    0 讨论(0)
  • 2020-12-30 05:53

    If I'd use the library, I would really hate to use both try-catch block and old style error checking. And even if the missing API key renders the library unusable, it's still part of application.

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