📜 ⬆️ ⬇️

Exceptions. Where do i use them

After reading “How to use exceptions” and comments to it I decided to write a short article where I use exceptions, and not as “correct”, everything is based on experience, briefly and concisely.


Logics


  1. Data validation: in other words, input data error, field format not the same, field not filled, field uniqueness error - all are input data errors, in such cases I throw an event listing all the fields and errors that are subsequently output to the user.
  2. 404 Document not found: If a specific entity was requested (for example, a line from a database) by its identifier (and not only), then if it is not present, an event is thrown, which later turns into page 404.
  3. 403 Access denied: If there was an attempt to access the user where he could not - then throws an exception (in the arguments you can pass why there is no access there), which later turns into 403.
  4. 401 Authorization Required: User requests data where authorization is required. We throw out the exception (in the arguments we can pass Relarm - the text of the authorization request), and the user receives either a request for HTTP authorization or a regular form.
  5. 301 Redirect: Need to redirect? We throw an ekpepshn - in it we transfer where it is necessary redirektit.

Errors


  1. Fatal errors: Everything is clear, there is no connection to the database, or the config cannot be read. Just write to the log and pokvyem deface.
  2. Critical errors: For example: SMS is not sent, the file cannot be uploaded - we throw a specific exception. but in the right places (for example, phone confirmation), we process it and write to the user that we cannot send SMS.

Debugging


In debug mode I use PHP_Exceptionizer ( discussed here ). Allows you to make the code cleaner, any notice and varning turns into an event, which in turn allows you not to miss them. Naturally this is included only in debug mode.

Example


I also recommend logging all the "misunderstood" exceptions:
')
class Controller_Front
{
//
public function execute()
{
try {
...
//
try {
... //
// .
throw new Controller_RedirectException( 'http://habr.ru' );
...
} catch (Controller_DataException $e) {
//
$ this ->errors = $e->getErrors();
}
...
} catch (Controller_RedirectException $e) {
// ,
$ this ->_processRedirectException($e);
} catch (Controller_AuthException $e) {
// , HTTP
$ this ->_processAuthException($e);
} catch (Exception $e) {
// .
$ this ->_logException($e);
// .
$ this ->_processFatalException($e);
}
}
}


* This source code was highlighted with Source Code Highlighter .


There is not enough karma to transfer to the PHP blog. Thanks for the karma, suffered.

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


All Articles