Have I to define custom exception class ItemValidAccess in mehod?

19 Views Asked by At

On laravel 10 site I made a method which returns true or ItemValidAccess exception in case of invalid data :

   /**
     * Determine whether logged user have access to complete item
     *
     * @param  \App\Models\Item  $item
     *
     * @return true | ItemValidAccess -
     */
    public static function onlyOwnerCanCompleteItem(Item $item): true | ItemValidAccess {
        throw_if(
            $item->creator_id !== Auth::user()->id,
            ItemValidAccess::class,
            __('You are not allowed to complete this item')
        );

        return true;
    }

Is it correct way to define ItemValidAccess in method description as there is no return statement when I run throw_if ?

"laravel/framework": "^10.34.2"

Thanks in advance!

1

There are 1 best solutions below

0
matiaslauriti On

If you only validate, it makes no sense to return true and nothing else. In those cases just do the validation and if it fails, throw the exception and done, because if it does not fail, of course you would get true back (adds no value at all), so your code should be like:

/**
 * Determine whether logged user have access to complete item
 *
 * @throws ItemValidAccess
 */
public static function onlyOwnerCanCompleteItem(Item $item): void {
    throw_if(
        $item->creator_id !== Auth::user()->id,
        ItemValidAccess::class,
        __('You are not allowed to complete this item')
    );
}

There is also one more "issue", if you throw an exception, it is an stardard to have Exception in the name: ItemInvalidAccessException makes more sense.