Better way of handling exceptions in Laravel: Trammel — Part 1

public function ajax()
{
return $this->isXmlHttpRequest();
}
...public function isXmlHttpRequest(): bool
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
public function isJson()
{
return Str::contains($this->header('CONTENT_TYPE') ?? '', ['/json', '+json']);
}
<?php

namespace App\Exceptions;

use Oguz\Trammel\Exception\BaseHandler;

class Handler extends BaseHandler
{
// Remove the render method in the class
}
<?php

declare(strict_types=1);

namespace App\Exceptions\Handlers;

use Symfony\Component\HttpFoundation\Response;
use Oguz\Trammel\Handlers\AjaxHandler;
use Illuminate\Http\Request;
use Throwable;

class CustomAjaxHandler extends AjaxHandler
{
protected function handle(Request $request, Throwable $exception): Response
{
return response()->json([
'success' => false,
'message' => 'Custom Ajax handler'
]);
}
}`
<?php

declare(strict_types=1);

namespace App\Exceptions\Handlers;

use Symfony\Component\HttpFoundation\Response;
use Oguz\Trammel\Handlers\AjaxValidationHandler;
use Illuminate\Http\Request;
use Throwable;

class CustomAjaxValidationHandler extends AjaxValidationHandler
{
protected function handle(Request $request, Throwable $exception): Response
{
return response()->json([
'success' => false,
'message' => 'Custom Ajax validation handler'
]);
}
}
> app
> Exceptions
> Handlers
CustomAjaxHandler.php
CustomAjaxValidationHandler.php
Handler.php
<?php

namespace App\Exceptions;

use App\Exceptions\Handlers\CustomAjaxValidationHandler;
use App\Exceptions\Handlers\CustomAjaxHandler;
use Oguz\Trammel\Exception\BaseHandler;

class Handler extends BaseHandler
{
protected array $handlers = [
CustomAjaxHandler::class,
CustomAjaxValidationHandler::class
];
// ...
// Remember no `render` function inside the class
// ...
}
protected function isResponsible(Request $request, Throwable $exception): bool
{
return $request->ajax() &&
$exception instanceof ValidationException;
}
protected function isResponsible(Request $request, Throwable $exception): bool
{
return $exception instanceof ValidationException;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store