Skip to content

Instantly share code, notes, and snippets.

@joseluisq
Last active January 3, 2022 13:22
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save joseluisq/bea6220cca5e1441d550b27409283497 to your computer and use it in GitHub Desktop.
Save joseluisq/bea6220cca5e1441d550b27409283497 to your computer and use it in GitHub Desktop.
Configure PHP Lumen 5 HTTP Exception Handlers with common JSON responses.

Lumen 5 HTTP Exception Handlers with JSON support.

Configure PHP Lumen 5 HTTP Exception Handlers with common JSON responses.

image

Setup

Copy (replace) only the attached files to their respective directories. app/Exceptions/Handler.php and app/Http/Middleware/Authenticate.php

Tip: Via your .env file you can handle the visibility of the HTTP Exception responses. APP_DEBUG=false (for display json exception responses in production)

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response()
->json([
'success' => false,
'status' => 401,
'message' => 'HTTP_UNAUTHORIZED'
], 401);
}
return $next($request);
}
}
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\Response;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
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 (env('APP_DEBUG')) {
return parent::render($request, $e);
}
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
if ($e instanceof HttpResponseException) {
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($e instanceof MethodNotAllowedHttpException) {
$status = Response::HTTP_METHOD_NOT_ALLOWED;
$e = new MethodNotAllowedHttpException([], 'HTTP_METHOD_NOT_ALLOWED', $e);
} elseif ($e instanceof NotFoundHttpException) {
$status = Response::HTTP_NOT_FOUND;
$e = new NotFoundHttpException('HTTP_NOT_FOUND', $e);
} elseif ($e instanceof AuthorizationException) {
$status = Response::HTTP_FORBIDDEN;
$e = new AuthorizationException('HTTP_FORBIDDEN', $status);
} elseif ($e instanceof \Dotenv\Exception\ValidationException && $e->getResponse()) {
$status = Response::HTTP_BAD_REQUEST;
$e = new \Dotenv\Exception\ValidationException('HTTP_BAD_REQUEST', $status, $e);
} elseif ($e) {
$e = new HttpException($status, 'HTTP_INTERNAL_SERVER_ERROR');
}
return response()->json([
'success' => false,
'status' => $status,
'message' => $e->getMessage()
], $status);
}
}
@lvidal1
Copy link

lvidal1 commented Jun 4, 2018

Do I need to enable Exception/Handler.php pn th app.php file? I'm using Lumen 5.6 and I've replaced Handler.php with your code however this seems not to work.

@gliesche
Copy link

gliesche commented Jun 8, 2018

If APP_DEBUG is set to true (see your .env file) you'll probably see the same page as before. Try changing it to false.

@azhe403
Copy link

azhe403 commented Jun 8, 2018

thanks, work in Lumen 5.6

@cdave3
Copy link

cdave3 commented Jul 7, 2018

What is the purpose of the $response variable in Handler.php?

@joseluisq
Copy link
Author

@AcidReign it's fixed now 👍

@iC00kScripts
Copy link

Thanks for this.... Quite helpful (Lumen 5.7)

@cyberbit
Copy link

Note for those using this code, I recommend replacing env('APP_DEBUG') with config('app.debug') as that will be more compatible with Laravel's environment caching. I've encountered issues in the past with env() not updating or returning null on some server setups after deployment.

@matteusbarbosa
Copy link

good standard. really fit for my needs. quite helpful. thanks

@matteusbarbosa
Copy link

this is kinda handler with steroids

@Schwarzion
Copy link

Hi, thanks for the work provided.
Working on Lumen 6, needed to change :
use Illuminate\Http\Exception\HttpResponseException;
to :
use Illuminate\Http\Exceptions\HttpResponseException;

Notify the 's' change in Exception, might be for norm.

@Oranzh
Copy link

Oranzh commented Jun 9, 2021

Thanks so much! It can work well for Lumen 8.x! @joseluisq

@saywan
Copy link

saywan commented Jan 3, 2022

Great

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