MaciejSuchanski's avatar

i dont understand exceptions laravel 12

HI, how do i handle exceptions? I must block ability to return error content (message, line, trace, file) to just something like 500 message: api error, and log the context to laravel.log or db. i want a global one, i don't want to have try catch blocks in every functions. i had a working code in laravel 10 but in 12 there is not even an exception.php file ...

0 likes
8 replies
Glukinho's avatar
Level 31

Laravel treats exceptions fine by default: set APP_DEBUG=false in .env and you will see only 500 (404, 403.. depends on the error itself) without specific error messages. The exception message itself is logged in storage/logs/laravel.log along with a backtrace, you can analyze the error there.

So, in simple case you don't have to handle them at all, just have APP_DEBUG=false and Laravel does the rest.

1 like
Tray2's avatar

Like @glukinho mentioned, for dev debug = true, for production, debug = false.

Dev

APP_ENV=local
APP_DEBUG=true 	

Prod

APP_ENV=production
APP_DEBUG=false
1 like
MaciejSuchanski's avatar

i made this and it works as i wanted. return Application::configure(basePath: dirname(DIR)) ->withRouting( api: DIR . '../../routes/api.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { $middleware->group('api', ['auth:api']); }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->render(function (Throwable $e): JsonResponse { return response()->json([ 'message' => 'Please contact administrator.', 'time_of_error' => Carbon::now()->toDateTimeString(), 'error' => config('app.debug') ? $e->getMessage() : null, ], 500); }); })->create();

MaciejSuchanski's avatar

@martinbean i want users to get time of error and error message on staging version and only hide it on production. i dont like the default behaviour of it. Also i want to insert the error to database. So it not really fine how it is handled by default.

MaciejSuchanski's avatar

@martinbean then aswell? error is error... Login in into server to read laravel text file every time is nonsense for me. This i don't need help with.

Please or to participate in this conversation.