Skip to content

Instantly share code, notes, and snippets.

@akondas
Created August 14, 2015 17:43
Show Gist options
  • Save akondas/0cd73e9615963c101198 to your computer and use it in GitHub Desktop.
Save akondas/0cd73e9615963c101198 to your computer and use it in GitHub Desktop.
Laravel 5.0 Exception Handler
<?php
namespace App\Exceptions;
use Exception;
use Slack;
use Whoops;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException',
];
/**
* Report or log an exception.
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $e
*/
public function report(Exception $e)
{
if ($e instanceof FatalErrorException) {
Slack::to('#fatalerros')->send(sprintf('File: %s; Line: %s; Message: %s', $e->getFile(), $e->getLine(), $e->getMessage()));
}
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if (config('app.debug')) {
return $this->renderDebug($request, $e);
} else {
$status = $this->getStatusByException($e);
if (view()->exists('errors.' . $status)) {
return response()->view("errors.{$status}", [], $status);
}
}
return parent::render($request, $e);
}
/**
* @param $request
* @param Exception $e
* @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
*/
protected function renderDebug($request, Exception $e)
{
if ($request->ajax()) {
return response()->json(['error' => [
'line' => $e->getLine(),
'file' => $e->getFile(),
'message' => $e->getMessage(),
]], 500);
}
return $this->renderExceptionWithWhoops($e);
}
/**
* @param Exception $e
* @return \Illuminate\Http\Response
*/
protected function renderExceptionWithWhoops(Exception $e)
{
$whoops = new Whoops\Run();
$whoops->pushHandler(new Whoops\Handler\PrettyPageHandler());
return response(
$whoops->handleException($e),
$e->getStatusCode(),
$e->getHeaders()
);
}
/**
* @param Exception $e
* @return int
*/
protected function getStatusByException(Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$status = 404;
} elseif ($e instanceof NotFoundHttpException) {
$status = 404;
} else {
$status = 500;
}
return $status;
}
}
@akondas
Copy link
Author

akondas commented Aug 14, 2015

Composer dependencies:

  • "filp/whoops": "~1.0"
  • "maknz/slack": "^1.7"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment