Code: Select all
use App\Livewire\BaseComponent;
class MyComponent extends BaseComponent
{
...
}
Code: Select all
abstract class BaseComponent extends \Livewire\Component
{
public function exception(\Throwable $e, \Closure $stopPropagation): void
{
if ($e instanceof ModelNotFoundException) {
Flux::toast(text: '...'));
$stopPropagation();
}
if ($e instanceof AuthorizationException) {
Flux::toast(text: 'Unauthorized'));
$stopPropagation();
}
}
}
Code: Select all
#[On('show-thing')]
public function showThing($id)
{
$thing = ThingModel::findOrFail($id);
}
Code: Select all
public function doThing(): void
{
Gate::authorize('do-thing');
}
Dies funktioniert auch in Javascript.
Code: Select all
window.dispatchEvent(new CustomEvent('show-thing', { detail: { id: -999 } })); // makes a toast pop up if -999 is not a valid id
Livewire.find('....').doThing() // makes a toast pop up if I'm not authorized
Was ich zu verhindern (oder vielmehr zu behandeln) versuche, sind Ausnahmen, die aufgrund eines fehlerhaften Methodenaufrufs ausgelöst werden.
Zum Beispiel, wenn versucht wird, die JS-Konsole zu öffnen und
auszuführen
Code: Select all
Livewire.first().unexistentMethod();
hinzufüge
Code: Select all
if ($e instanceof MethodNotFoundException) {
Log::warning('...')
$stopPropagation();
}
Die Ausnahme selbst wird innerhalb einer Livewire-Anbieterklasse ausgelöst.
Code: Select all
namespace Livewire\Mechanisms;
class HandleComponents extends Mechanism
{
...
protected function callMethods($root, $calls, $context)
{
$returns = [];
foreach ($calls as $idx => $call) {
$method = $call['method'];
$params = $call['params'];
$earlyReturnCalled = false;
$earlyReturn = null;
$returnEarly = function ($return = null) use (&$earlyReturnCalled, &$earlyReturn) {
$earlyReturnCalled = true;
$earlyReturn = $return;
};
$finish = trigger('call', $root, $method, $params, $context, $returnEarly);
if ($earlyReturnCalled) {
$returns[] = $finish($earlyReturn);
continue;
}
$methods = Utils::getPublicMethodsDefinedBySubClass($root);
// Also remove "render" from the list...
$methods = array_values(array_diff($methods, ['render']));
// @todo: put this in a better place:
$methods[] = '__dispatch';
if (! in_array($method, $methods)) {
throw new MethodNotFoundException($method);
}
if (config('app.debug')) $start = microtime(true);
$return = wrap($root)->{$method}(...$params);
if (config('app.debug')) trigger('profile', 'call'.$idx, $root->getId(), [$start, microtime(true)]);
$returns[] = $finish($return);
}
$context->addEffect('returns', $returns);
}
}
Mobile version