setup handler exception
This commit is contained in:
@@ -2,7 +2,12 @@
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
@@ -47,4 +52,59 @@ class Handler extends ExceptionHandler
|
||||
//
|
||||
});
|
||||
}
|
||||
|
||||
public function render($request, Throwable $exception)
|
||||
{
|
||||
if ($request->wantsJson()) {
|
||||
if ($exception instanceof AuthenticationException) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => 'Unauthenticated',
|
||||
'errors' => [
|
||||
'Unauthenticated'
|
||||
]
|
||||
], 401);
|
||||
}
|
||||
|
||||
if ($exception instanceof AuthorizationException) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => 'This action is unauthorized.',
|
||||
'errors' => [
|
||||
'This action is unauthorized.'
|
||||
]
|
||||
], 403);
|
||||
}
|
||||
|
||||
if ($exception instanceof NotFoundHttpException) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => 'Route Not Found',
|
||||
'errors' => [
|
||||
'Route Not Found'
|
||||
]
|
||||
], 404);
|
||||
}
|
||||
|
||||
if ($exception instanceof ModelNotFoundException) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => 'Record for ' . str_replace('App', '', str_replace('\\Models\\', '', $exception->getModel())) . ' not found',
|
||||
'errors' => [
|
||||
'Record for ' . str_replace('App', '', str_replace('\\Models\\', '', $exception->getModel())) . ' not found'
|
||||
]
|
||||
], 404);
|
||||
}
|
||||
|
||||
if ($exception instanceof ValidationException) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => 'The given data was invalid.',
|
||||
'errors' => collect($exception->errors())->flatten()
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
|
||||
return parent::render($request, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user