Welcome Guest, Not a member yet? Register   Sign In
Throw me. Unhandled exception

I don't know who invented this magic, but it seems to me that it has gotten out of control.
This is an exception class that has static methods that throw an exception with different messages.
The problem is that in some cases, some exceptions are not exceptions at all, but a valid state. 
But there is no way to separate the wheat from the chaff.

For example, the application considers that if the user tries to update the data and the data does not differ from the original, then this is not considered an error. 
The model throws DataException::forEmptyDataset() in this case, but it is not possible to specifically catch the "forEmptyDataset" exception.
The same class for all exceptions of this type, only the messages are different.

It seems to me that it is worth defining constants with the exception code and passing them to the constructor.

PHP Code:
class DataException extends RuntimeException implements ExceptionInterface
    use DebugTraceableTrait;
    const EMPTY_PRIMARY_KEY 2;

    public static function forEmptyDataset(string $mode)
        return new static(lang('Database.emptyDataset', [$mode]), self::EMPTY_DATA_SET);

    public static function forEmptyPrimaryKey(string $mode)
        return new static(lang('Database.emptyPrimaryKey', [$mode]), self::EMPTY_PRIMARY_KEY);

Now it is possible to determine the context of an exception by code.
PHP Code:
$post = ['a' => 1];
$entity->fill($post); // The entity already contains ['a' => 1] before filling

try {
    (new SomeModel())->update($id$entity->toRawArray(true)); //only changes
} catch (DataException $e) {

    if ($e->getCode() !== DataException::EMPTY_DATA_SET) {
        throw new DataException($e->getMessage(), $e->getCode());

    $msg 'Update successful';


I don't like magic. Creating sub-classes for each case, it is simple.

But the magic is the CI4 way, it is better having error code constants.

Theme © iAndrew 2016 - Forum software by © MyBB