Skip to content

Commit

Permalink
feat: improve exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammad-Alavi committed Apr 15, 2022
1 parent 95c013f commit 30fcbca
Showing 1 changed file with 34 additions and 16 deletions.
50 changes: 34 additions & 16 deletions app/Ship/Exceptions/Handlers/ExceptionsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
namespace App\Ship\Exceptions\Handlers;

use Apiato\Core\Abstracts\Exceptions\Exception as CoreException;
use Apiato\Core\Exceptions\AuthenticationException;
use Apiato\Core\Exceptions\Handlers\ExceptionsHandler as CoreExceptionsHandler;
use App\Ship\Exceptions\NotFoundException;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

/**
Expand Down Expand Up @@ -44,23 +49,36 @@ public function register(): void
});

$this->renderable(function (CoreException $e) {
if (config('app.debug')) {
$response = [
'message' => $e->getMessage(),
'errors' => $e->getErrors(),
'exception' => static::class,
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
];
} else {
$response = [
'message' => $e->getMessage(),
'errors' => $e->getErrors(),
];
}
return $this->buildResponse($e);
});

$this->renderable(function (NotFoundHttpException $e) {
return $this->buildResponse(new NotFoundException());
});

return response()->json($response, $e->getCode());
$this->renderable(function (AccessDeniedHttpException $e) {
return $this->buildResponse(new AuthenticationException());
});
}

private function buildResponse(CoreException $e): JsonResponse
{
if (config('app.debug')) {
$response = [
'message' => $e->getMessage(),
'errors' => $e->getErrors(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
];
} else {
$response = [
'message' => $e->getMessage(),
'errors' => $e->getErrors(),
];
}

return response()->json($response, (int)$e->getCode());
}
}

0 comments on commit 30fcbca

Please sign in to comment.