Skip to content

Instantly share code, notes, and snippets.

@osibg
Last active June 20, 2021 06:27
Show Gist options
  • Save osibg/8ace6831e978e916b9d2f578f55f073a to your computer and use it in GitHub Desktop.
Save osibg/8ace6831e978e916b9d2f578f55f073a to your computer and use it in GitHub Desktop.
Handlers for Exceptions
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
class AuthenticationException
{
public function __invoke(\Exception $exception): ?JsonResponse
{
return response()->json(['error' => 'Unauthorized: Access is denied due to invalid credentials.'], 401);
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
class AuthorizationException
{
public function __invoke(\Illuminate\Auth\Access\AuthorizationException $exception): ?JsonResponse
{
return response()->json(['error' => 'Insufficient privileges to perform this action'], 403);
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileIsTooBig;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileUnacceptableForCollection;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\RequestDoesNotHaveFile;
use Spatie\MediaLibrary\Helpers\File;
class FileCannotBeAdded
{
public function __invoke(\Spatie\MediaLibrary\Exceptions\FileCannotBeAdded $exception): ?JsonResponse
{
if ($exception instanceof FileIsTooBig) {
$maxFileSize = File::getHumanReadableSize(config('medialibrary.max_file_size'));
return response()->json(['error' => "File is greater than the maximum allowed {$maxFileSize}"], 413);
}
if ($exception instanceof RequestDoesNotHaveFile) {
$maxFileSize = File::getHumanReadableSize(config('medialibrary.max_file_size'));
return response()->json(['error' => "Please upload file less than {$maxFileSize}"], 413);
}
if ($exception instanceof FileUnacceptableForCollection) {
$maxFileSize = File::getHumanReadableSize(config('medialibrary.max_file_size'));
return response()->json(['error' => "Please upload file less than {$maxFileSize}"], 413);
}
if ($exception instanceof FileUnacceptableForCollection) {
return response()->json(['error' => 'The file format is not allowed'], 415);
}
return null;
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
class MethodNotAllowedHttpException
{
public function __invoke(\Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException $exception): ?JsonResponse
{
return response()->json((['error' => 'Method Not Allowed']), 405);
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Database\Eloquent;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
class ModelNotFoundException
{
public function __invoke(Eloquent\ModelNotFoundException $exception): JsonResponse
{
if (empty($exception->getMessage()) || Str::startsWith($exception->getMessage(), 'No query results for model')) {
$modelName = class_basename($exception->getModel());
$message = sprintf("No results for %s", $modelName);
if (!empty($exception->getIds())) {
$idsString = implode(', ', (array)$exception->getIds());
$modelKey = App::make($exception->getModel())->getKeyName();
$message .= sprintf(" with {$modelKey} %s", $idsString);
}
} else {
$message = $exception->getMessage();
}
return response()->json([
'error' => 'The requested entity was not found',
'messages' => [$message]
], 404);
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Database\Eloquent;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
class NotFoundHttpException
{
public function __invoke(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception): JsonResponse
{
return response()->json(['error' => 'The requested resource was not found'], 404);
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
class QueryException
{
const ERROR_CODE_DB_QUERY_UNIQUE_CONSTRAINT_VIOLATION = 1062;
public function __invoke(\Illuminate\Database\QueryException $exception): ?JsonResponse
{
$errorCode = $exception->errorInfo[1];
if ($errorCode == self::ERROR_CODE_DB_QUERY_UNIQUE_CONSTRAINT_VIOLATION) {
return response()->json([
'error' => "Entry cannot be created because already exists"
], 400);
}
return null;
}
}
<?php
namespace App\Exceptions\Handlers;
use GuzzleHttp\Exception\RequestException as GuzzleRequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
class RequestException
{
const CLIENT_NOT_FOUND_EXCEPTION_MESSAGE = 'No entity satisfies the condition.';
public function __invoke(GuzzleRequestException $exception): ?JsonResponse
{
Log::error('GuzzleRequestException: ' . $exception->getMessage());
$response = $exception->getResponse();
if (isset($response)) {
$body = $response->getBody();
Log::error('Code: ' . $response->getStatusCode());
if (isset($body)) {
$content = $body->getContents();
Log::error('Body: ' . $content);
$jsonDecoded = json_decode($content, true);
if (!empty($jsonDecoded['exceptionMessage'])) {
if ($jsonDecoded['exceptionMessage'] == self::CLIENT_NOT_FOUND_EXCEPTION_MESSAGE) {
return response()->json(['error' => 'The requested resource was not found'], 404);
}
return response()->json([
'error' => $jsonDecoded['exceptionMessage']
], '400');
}
}
}
return null;
}
}
<?php
namespace App\Exceptions\Handlers;
use Illuminate\Http\JsonResponse;
class ValidationException
{
public function __invoke(\Illuminate\Validation\ValidationException $exception): ?JsonResponse
{
$errors = array_map(function ($message): string {
return is_array($message) ? reset($message) : $message;
}, $exception->errors());
return response()->json(['error' => 'Invalid fields', 'messages' => $errors], 400);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment