<?php
public function render($request, Throwable $exception)
{
if ($request->is('api/*')) {
return $this->handleApiException($exception);
}
return parent::render($request, $exception);
}
protected function handleApiException(Throwable $exception)
{
switch (true) {
case $exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException:
return response()->json(['error' => 'Model not found'], 404);
case $exception instanceof \Illuminate\Validation\ValidationException:
return response()->json(['error' => 'Validation failed', 'errors' => $exception->errors()], 422);
case $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException:
return response()->json(['error' => 'Not Found'], 404);
case $exception instanceof \Illuminate\Auth\AuthenticationException:
return response()->json(['error' => 'Unauthenticated'], 401);
case $exception instanceof \Illuminate\Auth\Access\AuthorizationException:
return response()->json(['error' => 'Unauthorized'], 403);
case $exception instanceof \Illuminate\Session\TokenMismatchException:
return response()->json(['error' => 'CSRF token mismatch'], 419);
default:
return $this->genericApiError();
}
}
protected function genericApiError()
{
return response()->json(['error' => 'Something went wrong'], 500);
}