Skip to content

Commit

Permalink
Clean up old excception handling in httpkernel
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelfolaron committed Aug 16, 2024
1 parent 199ce6d commit 6358e85
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 151 deletions.
29 changes: 22 additions & 7 deletions app/Core/Events.php
Original file line number Diff line number Diff line change
Expand Up @@ -520,15 +520,20 @@ public function listen($events, $listener = null) {}
* @param string $eventName
* @return bool
*/
public function hasListeners($eventName) {}
public function hasListeners($eventName) {
throw new \Exception("Not implemented");
return false;
}

/**
* Register an event subscriber with the dispatcher.
*
* @param object|string $subscriber
* @return void
*/
public function subscribe($subscriber) {}
public function subscribe($subscriber) {
throw new \Exception("Not implemented");
}

/**
* Dispatch an event until the first non-null response is returned.
Expand All @@ -537,7 +542,9 @@ public function subscribe($subscriber) {}
* @param mixed $payload
* @return mixed
*/
public function until($event, $payload = []) {}
public function until($event, $payload = []) {
throw new \Exception("Not implemented");
}


/**
Expand All @@ -547,28 +554,36 @@ public function until($event, $payload = []) {}
* @param array $payload
* @return void
*/
public function push($event, $payload = []) {}
public function push($event, $payload = []) {
throw new \Exception("Not implemented");
}

/**
* Flush a set of pushed events.
*
* @param string $event
* @return void
*/
public function flush($event) {}
public function flush($event) {
throw new \Exception("Not implemented");
}

/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event) {}
public function forget($event) {
throw new \Exception("Not implemented");
}

/**
* Forget all of the queued listeners.
*
* @return void
*/
public function forgetPushed() {}
public function forgetPushed() {
throw new \Exception("Not implemented");
}
}
111 changes: 11 additions & 100 deletions app/Core/ExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Reflector;
use Illuminate\Support\Traits\ReflectsClosures;
use Illuminate\Support\ViewErrorBag;
Expand Down Expand Up @@ -81,16 +82,10 @@ class ExceptionHandler implements ExceptionHandlerContract
* @var string[]
*/
protected $internalDontReport = [
AuthenticationException::class,
AuthorizationException::class,
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
MultipleRecordsFoundException::class,
RecordsNotFoundException::class,
SuspiciousOperationException::class,
TokenMismatchException::class,
ValidationException::class,
];

/**
Expand Down Expand Up @@ -234,20 +229,16 @@ public function report(Throwable $e)
}
}

try {
$logger = $this->container->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $e;
}

$logger->error(
Log::error(
$e->getMessage(),
array_merge(
$this->exceptionContext($e),
$this->context(),
['exception' => $e]
)
);

}

/**
Expand Down Expand Up @@ -300,8 +291,7 @@ protected function context()
{
try {
return array_filter([
'userId' => Auth::id(),
// 'email' => optional(Auth::user())->email,

]);
} catch (Throwable $e) {
return [];
Expand Down Expand Up @@ -341,10 +331,6 @@ public function render($request, Throwable $e)

if ($e instanceof HttpResponseException) {
return $e->getResponse();
} elseif ($e instanceof AuthenticationException) {
return $this->unauthenticated($request, $e);
} elseif ($e instanceof ValidationException) {
return $this->convertValidationExceptionToResponse($e, $request);
}

return $this->shouldReturnJson($request, $e)
Expand Down Expand Up @@ -377,82 +363,10 @@ protected function mapException(Throwable $e)
*/
protected function prepareException(Throwable $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new AccessDeniedHttpException($e->getMessage(), $e);
} elseif ($e instanceof TokenMismatchException) {
$e = new HttpException(419, $e->getMessage(), $e);
} elseif ($e instanceof SuspiciousOperationException) {
$e = new NotFoundHttpException('Bad hostname provided.', $e);
} elseif ($e instanceof RecordsNotFoundException) {
$e = new NotFoundHttpException('Not found.', $e);
}

return $e;
}

/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $this->shouldReturnJson($request, $exception)
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest($exception->redirectTo() ?? route('login'));
}

/**
* Create a response object from the given validation exception.
*
* @param \Illuminate\Validation\ValidationException $e
* @param \Illuminate\Http\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}

return $this->shouldReturnJson($request, $e)
? $this->invalidJson($request, $e)
: $this->invalid($request, $e);
}

/**
* Convert a validation exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\Response
*/
protected function invalid($request, ValidationException $exception)
{
return redirect($exception->redirectTo ?? url()->previous())
->withInput(Arr::except($request->input(), $this->dontFlash))
->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag));
}

/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}

/**
* Determine if the exception handler response should be JSON.
*
Expand Down Expand Up @@ -573,16 +487,13 @@ protected function renderExceptionWithSymfony(Throwable $e, $debug)
*/
protected function renderHttpException(HttpExceptionInterface $e)
{
//$this->registerErrorViewPaths();

if (view()->exists($view = $this->getHttpExceptionView($e))) {
return response()->view($view, [
'errors' => new ViewErrorBag(),
'exception' => $e,
], $e->getStatusCode(), $e->getHeaders());
try {
$view = $this->getHttpExceptionView($e);
return app()->make(Template::class)->display($view, "error", $e->getStatusCode());
}catch(Throwable $e){
return $this->convertExceptionToResponse($e);
}

return $this->convertExceptionToResponse($e);
}

/**
Expand All @@ -592,7 +503,7 @@ protected function renderHttpException(HttpExceptionInterface $e)
*/
protected function registerErrorViewPaths()
{
(new RegisterErrorViewPaths())();

}

/**
Expand All @@ -603,7 +514,7 @@ protected function registerErrorViewPaths()
*/
protected function getHttpExceptionView(HttpExceptionInterface $e)
{
return "error/error{$e->getStatusCode()}";
return "errors.error{$e->getStatusCode()}";
}

/**
Expand Down
55 changes: 15 additions & 40 deletions app/Core/HttpKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,49 +54,24 @@ public function handle($request)
{
$this->requestStartedAt = microtime(true);

try {

//Main Pipeline
$response = (new Pipeline($this->app))
//Main Pipeline
$response = (new Pipeline($this->app))
->send($request)
->through($this->getMiddleware())
->then(fn ($request) =>
//Then run through plugin pipeline
(new Pipeline($this->app))
->send($request)
->through($this->getMiddleware())
->then(fn ($request) =>
//Then run through plugin pipeline
(new Pipeline($this->app))
->send($request)
->through(self::dispatch_filter(
hook: 'plugins_middleware',
payload: [],
function: 'handle',
))
->then(fn () => Frontcontroller::dispatch_request($request))
);

return self::dispatch_filter('beforeSendResponse', $response);

} catch (HttpResponseException $e) {
report($e);
return $e->getResponse();
} catch (\Throwable $e) {

report($e);

if (! $this->app->make(Environment::class)->debug) {

return $this->app->make(Template::class)->display('errors.error500', 'error');
}
->through(self::dispatch_filter(
hook: 'plugins_middleware',
payload: [],
function: 'handle',
))
->then(fn () => Frontcontroller::dispatch_request($request))
);

if ($request instanceof HtmxRequest) {
/** @todo Replace with a proper error template for htmx requests */
return new Response(sprintf(
'<dialog style="%s" open>%s</dialog>',
'width: 90vw; height: 90vh; z-index: 9999999; position: fixed; top: 5vh; left: 5vh; overflow: scroll',
(new HtmlErrorRenderer(true))->render($e)->getAsString(),
));
}
return self::dispatch_filter('beforeSendResponse', $response);

throw $e;
}
}

/**
Expand Down
2 changes: 2 additions & 0 deletions app/Core/IncomingRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ public function expectsJson()
if($this instanceof CliRequest || $this->isApiOrCronRequest()) {
return true;
}

return false;
}

}
4 changes: 0 additions & 4 deletions blocklist.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
"tw-absolute",
"tw-relative",
"tw-sticky",
"tw-left-0",
"tw-right-[10px]",
"tw-top-0",
"tw-top-[10px]",
"tw-top-[50px]",
"tw-z-10",
"tw-z-20",
"tw-float-right",
Expand All @@ -17,7 +15,6 @@
"tw-mb-l",
"tw-mb-m",
"tw-ml-0",
"tw-ml-[100px]",
"tw-ml-[10px]",
"tw-ml-base",
"tw-ml-m",
Expand Down Expand Up @@ -69,7 +66,6 @@
"tw-bg-primary",
"tw-bg-red-500",
"tw-bg-yellow-500",
"tw-p-0",
"tw-p-[10px]",
"tw-p-m",
"tw-p-none",
Expand Down

0 comments on commit 6358e85

Please sign in to comment.