fix handler response

This commit is contained in:
Muhammad Fajar
2022-10-31 07:08:03 +07:00
parent e025675210
commit 9224bcef5b

View File

@@ -7,6 +7,7 @@ use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
@@ -59,49 +60,54 @@ class Handler extends ExceptionHandler
if ($exception instanceof AuthenticationException) {
return response()->json([
'status' => 'error',
'statusCode' => Response::HTTP_UNAUTHORIZED,
'message' => 'Unauthenticated',
'errors' => [
'Unauthenticated'
]
], 401);
], Response::HTTP_UNAUTHORIZED);
}
if ($exception instanceof AuthorizationException) {
return response()->json([
'status' => 'error',
'statusCode' => Response::HTTP_FORBIDDEN,
'message' => 'This action is unauthorized.',
'errors' => [
'This action is unauthorized.'
]
], 403);
], Response::HTTP_FORBIDDEN);
}
if ($exception instanceof NotFoundHttpException) {
return response()->json([
'status' => 'error',
'statusCode' => Response::HTTP_NOT_FOUND,
'message' => 'Route Not Found',
'errors' => [
'Route Not Found'
]
], 404);
], Response::HTTP_NOT_FOUND);
}
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'status' => 'error',
'statusCode' => Response::HTTP_NOT_FOUND,
'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);
], Response::HTTP_NOT_FOUND);
}
if ($exception instanceof ValidationException) {
return response()->json([
'status' => 'error',
'statusCode' => Response::HTTP_UNPROCESSABLE_ENTITY,
'message' => 'The given data was invalid.',
'errors' => collect($exception->errors())->flatten()
], 422);
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
}