refactor: enhance handleAction method to include error route parameter for improved error handling

This commit is contained in:
Yoga Pangestu 2026-08-01 00:50:52 +07:00
parent 5b553b2c26
commit e92a4cfbcf
2 changed files with 8 additions and 7 deletions

View File

@ -16,20 +16,20 @@ public function __construct(
public function pay(Payroll $payroll): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->pay($payroll),
fn() => $this->service->pay($payroll),
'Gaji berhasil dibayar.',
'admin.finance.payroll-periods.show',
['payroll_period' => $payroll->payroll_period_id]
parameters: ['payroll_period' => $payroll->payroll_period_id]
);
}
public function cancel(Payroll $payroll): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->cancel($payroll),
fn() => $this->service->cancel($payroll),
'Gaji berhasil dibatalkan.',
'admin.finance.payroll-periods.show',
['payroll_period' => $payroll->payroll_period_id]
parameters: ['payroll_period' => $payroll->payroll_period_id]
);
}
}

View File

@ -8,18 +8,19 @@
abstract class Controller
{
protected function handleAction(callable $action, string $successMessage, string $redirectRoute, array $parameters = []): RedirectResponse
protected function handleAction(callable $action, string $successMessage, string $redirectRoute, ?string $errorRoute = null, array $parameters = []): RedirectResponse
{
try {
$action();
Inertia::flash('toast', ['type' => 'success', 'message' => $successMessage]);
return to_route($redirectRoute, $parameters);
} catch (ValidationException $e) {
$firstError = collect($e->errors())->flatten()->first();
Inertia::flash('toast', ['type' => 'error', 'message' => $firstError ?? 'Terjadi kesalahan.']);
return to_route($errorRoute ?? $redirectRoute, $parameters);
} catch (\Exception $e) {
Inertia::flash('toast', ['type' => 'error', 'message' => $e->getMessage()]);
return to_route($errorRoute ?? $redirectRoute, $parameters);
}
return to_route($redirectRoute, $parameters);
}
}