Skip to content

Instantly share code, notes, and snippets.

@cballou
Last active September 12, 2021 10:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cballou/8771765cedcb241145fb82086bde785e to your computer and use it in GitHub Desktop.
Save cballou/8771765cedcb241145fb82086bde785e to your computer and use it in GitHub Desktop.
Global handling of Laravel exceptions to better support AJAX requests.
<?php namespace App\Exceptions;
use Log;
use Mail;
use Config;
use Exception;
use Illuminate\Auth\Access\UnauthorizedException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return mixed
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* Note that UnauthorizedException is Laravel 5.4.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
}
$msg = null;
if ($e instanceof TokenMismatchException) {
$msg = 'Your session token had expired. Please try again.';
} else if ($e instanceof UnauthorizedException) {
$msg = 'You are not authorized to perform the previous action.';
}
if (!is_null($msg)) {
if ($request->ajax()) {
// return an appropriate response message
return response()->json(['error' => $msg], 403);
} else {
// redirect back to the page that caused the error
return redirect()
->back()
->withErrors(['error' => $msg])
->withInput();
}
}
return parent::render($request, $e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment