Skip to content

Instantly share code, notes, and snippets.

@SunDi3yansyah
Forked from joseluisq/1README.md
Last active October 22, 2018 17:13
Show Gist options
  • Select an option

  • Save SunDi3yansyah/5765b8ae0169379aaf8a4ca8937a84dd to your computer and use it in GitHub Desktop.

Select an option

Save SunDi3yansyah/5765b8ae0169379aaf8a4ca8937a84dd 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
{
/**
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* @param Exception $exception
* @throws Exception
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* @param \Illuminate\Http\Request $request
* @param Exception $exception
* @return \Illuminate\Http\JsonResponse|Response
*/
public function render($request, Exception $exception)
{
if (env('APP_DEBUG')) {
return parent::render($request, $exception);
}
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
if ($exception instanceof HttpResponseException) {
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($exception instanceof MethodNotAllowedHttpException) {
$status = Response::HTTP_METHOD_NOT_ALLOWED;
$exception = new MethodNotAllowedHttpException([], 'HTTP_METHOD_NOT_ALLOWED', $exception);
} elseif ($exception instanceof NotFoundHttpException) {
$status = Response::HTTP_NOT_FOUND;
$exception = new NotFoundHttpException('HTTP_NOT_FOUND', $exception);
} elseif ($exception instanceof ModelNotFoundException) {
$status = Response::HTTP_NOT_FOUND;
$exception = new NotFoundHttpException('HTTP_NOT_FOUND', $exception);
} elseif ($exception instanceof AuthorizationException) {
$status = Response::HTTP_FORBIDDEN;
$exception = new AuthorizationException('HTTP_FORBIDDEN', $status);
} elseif ($exception instanceof \Dotenv\Exception\ValidationException && $exception->getResponse()) {
$status = Response::HTTP_BAD_REQUEST;
$exception = new \Dotenv\Exception\ValidationException('HTTP_BAD_REQUEST', $status, $exception);
} elseif ($exception instanceof \ErrorException) {
$exception = new HttpException($status, 'HTTP_INTERNAL_SERVER_ERROR');
} elseif ($exception) {
$exception = new HttpException($status, 'HTTP_INTERNAL_SERVER_ERROR');
}
return response()->json([
'response' => ([
'status' => $status,
'message' => http_status_codes($status),
]),
'data' => [
'message' => http_status_codes($status),
'exception_trace' => (env('APP_ENV') != 'production') ? $exception->getTrace() : 'Disabled for ' . env('APP_ENV'),
]
], $status);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment