Skip to content

Instantly share code, notes, and snippets.

@AlphaRomeoMike
Created May 2, 2024 05:48
Show Gist options
  • Save AlphaRomeoMike/da276bc03a7bd68d1bba7db77aa7b126 to your computer and use it in GitHub Desktop.
Save AlphaRomeoMike/da276bc03a7bd68d1bba7db77aa7b126 to your computer and use it in GitHub Desktop.
Laravel bootstrap.app.php
<?php
use App\Error;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
api: __DIR__ . '/../routes/api.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (HttpException $e, Request $request) {
if ($e instanceof UnauthorizedHttpException) {
return response()->json([
'error' => $e->getMessage(),
'message' => Error::UNAUTHORIZED,
'status' => Response::HTTP_UNAUTHORIZED,
'type' => get_class($e)
], Response::HTTP_BAD_REQUEST);
}
if ($e instanceof BadRequestHttpException) {
return response()->json([
'error' => $e->getMessage(),
'message' => Error::BAD_REQUEST,
'status' => Response::HTTP_BAD_REQUEST,
'type' => get_class($e)
], Response::HTTP_BAD_REQUEST);
}
});
$exceptions->render(function (ValidationException $e, Request $request) {
if ($e instanceof ValidationException) {
return response()->json([
'error' => $e->getMessage(),
'message' => Error::BAD_REQUEST,
'status' => Response::HTTP_BAD_REQUEST,
'type' => get_class($e)
], Response::HTTP_BAD_REQUEST);
}
});
$exceptions->render(function (AuthenticationException $e, Request $request) {
return response()->json([
'error' => $e->getMessage(),
'message' => Error::UNAUTHORIZED,
'status' => Response::HTTP_UNAUTHORIZED,
'type' => get_class($e)
], Response::HTTP_UNAUTHORIZED);
});
$exceptions->render(function (Exception $e, Request $request) {
return response()->json([
'error' => Str::before($e->getMessage(), ':'),
'error' => $e->getMessage(),
'message' => Error::INTERNAL_SERVER_ERROR,
'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
'type' => get_class($e)
], Response::HTTP_INTERNAL_SERVER_ERROR);
});
})->create();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment