Skip to content

Instantly share code, notes, and snippets.

@arlanram
Created March 28, 2021 09:05
Show Gist options
  • Save arlanram/872c3ab9a5d56756f9a40a3d9fb564de to your computer and use it in GitHub Desktop.
Save arlanram/872c3ab9a5d56756f9a40a3d9fb564de to your computer and use it in GitHub Desktop.
Laravel: global handler with clean json structure and get complete error stacktrace from native server. Use api.php in routes dir
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
public function register()
{
//change Throwable to Exception if needed
$this->renderable(function (\Throwable $e, $request) {
return json_response(false, $e->getMessage(), $this->prepareJsonResponse($request, $e)->getStatusCode());
});
}
}
<?php
//include this fn in composer.json into autoload -> files -> ["app/helpers.php"] and then run composer dump-autoload
if (!function_exists('json_response')) {
function json_response(bool $status, string $message = 'No message', int $code = 200) {
return response()->json([
'ok' => $status,
'msg' => $message,
'code' => $code,
], $code);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment