setup handler exception

This commit is contained in:
Muhammad Fajar
2022-10-28 11:13:56 +07:00
parent 302cc343fd
commit 03fdf2684d
3 changed files with 152 additions and 2 deletions

View File

@@ -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);
}
}