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

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_DATA_SET 1;
    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';

Reply


Messages In This Thread
Throw me. Unhandled exception - by iRedds - 02-04-2021, 01:01 AM
RE: Throw me. Unhandled exception - by kenjis - 02-04-2021, 05:45 PM



Theme © iAndrew 2016 - Forum software by © MyBB