T
T
thorii2016-10-01 20:28:15
PHP
thorii, 2016-10-01 20:28:15

How crooked is it to work with Error and Exception like this?

Methods for handling both errors (set error handler) and exceptions (set exception handler) are concentrated in one class

namespace System\Core\Errors;

use \ErrorException;
use \Throwable;

class ErrorTrap
{
    public function __construct()
    {
        set_exception_handler([__CLASS__, 'exceptionHandler']);
        set_error_handler([__CLASS__, 'errorHandler']);
    }

    public function exceptionHandler(Throwable $exception) 
    {
        //Тут пишется лог исключения (Для error отдельный лог как и для исключений)
        //И отправка на e-mail/sms-gate информации о сбое 
    }

    public function errorHandler($severity, $msg, $file, $line)
    {
        if (!(error_reporting() & $severity)) return;
        throw new ErrorException($msg, 0, $severity, $file, $line);
    }
}

I suspect that this is very crooked, because the logic of working with errors and exceptions is mixed in one class (or am I wrong?). Do they need to be scattered across classes in order to observe at least a little the principle of single responsibility?
And is it possible to convert errors in general in this way into exceptions (probably yes, but not sure)?
And yet, with the advent of Throwable, is it necessary to produce such a baseException / NotFoundException ... (if so, through the Throwable implementation?)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2016-10-01
@thorii

No, it's not particularly ugly. In fact, here is the logic of handling unforeseen situations, but it’s errors or exceptions anyway. No need to spread a couple of lines across classes. That's what you will do with exceptions already need to be taken out. Separate display in HTML, CLI, logger in e-mail and SMS.
Yes, errors can be converted to exceptions before the advent of PHP 7, everyone did this.
Throwable appeared in order to be able to catch everything, both exceptions and new errors (also exceptions). Whether you need to produce an exception hierarchy depends only on your needs, and not on the appearance of the interface. If you need to generalize your exceptions, make them inherit from the base exception, or implement the base interface. If you just need an exception, inherit Exception, if you need an error, inherit Error. No need to produce a third entity, not fish, not meat, implanting Throwable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question