Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

scala's avatar
Level 1

display exception message in a secure and proper way

When my code has some exceptions, the exceptions are printed in the whole browser page showing extra information, code etc. Please see the image attached herewith.

How can I catch the exception messages and show inside a div? Also is there any way I can log my exceptions in database? Image url :: https://ibb.co/mQW7z8

0 likes
7 replies
tykus's avatar

Set APP_DEBUG=false in your .env file.

scala's avatar
Level 1

@tykus I do not want to disable debugger but want to print the exceptions in a user friendly way. Thank You

tykus's avatar

user friendly to whom; the developer or the end user?

tykus's avatar

Whether it is your own Exception class or something from inside the framework, you can check for the type and return your preferred response/view:

// app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
    if ($exception instanceof \Some\Exception::class) {
        return view(
            'error.view', // your custom view 
            ['message' => $exception->getMessage()], // any data you want to send to the view
            $e->getCode() // exception code
        );
    }

    return parent::render($request, $exception);
}

If you find that you are checking for a lot of custom exceptions inside Handler.php, then you could choose to define a render method inside your own custom class, and return the response from there:

// app/Exceptions/YourCustomException.php
public function render($request, Exception $exception)
{
    return view(
        'error.view', // your custom view 
        ['message' => $exception->getMessage()], // any data you want to send to the view
        $e->getCode() // exception code
    );
}

https://laravel.com/docs/5.6/errors#render-method

Thyrosis's avatar

@scala if your showing output to the end user, your application is in production mode and app_debug should be false by definition.

Live or production environments should never have app_debug to true imho, for exactly the reason you are now asking for another way around it.

Please or to participate in this conversation.