Last active
August 7, 2024 13:10
-
-
Save cballou/8771765cedcb241145fb82086bde785e to your computer and use it in GitHub Desktop.
Global handling of Laravel exceptions to better support AJAX requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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