Home > Mobile >  How to print custom message in try catch - php laravel
How to print custom message in try catch - php laravel

Time:03-02

I need to write to log some data when exception occurred, since it is dynamic data and I need the message I tried with simple code, just to write 'Boom' if exception occurred. However just the automatic exception data written in logs (as before the try catch). can someone advise how to print to log in the catch? I just need to add additional text to the exception, just to be more specific

try {
    $sheet->setCellValue($cell,$innervalue);
} catch(Exception $e) {
    $message = 'Can not set value: '.$innervalue .' in cell ' .$cell .$headerArray[$headerIndex];
    \Log::info('boom');
}

and in the logs nothing displayed enter image description here

CodePudding user response:

php artisan make:Exception SomeAweSomeException

This way you have your own controle of how the exception should look and handle. Also you can use standards wich makes you code look cleaner.

class SomeCustomException extends Exception
{
    // ...
 
    /**
     * Get the exception's context information.
     *
     * @return array
     */
    public function context()
    {
        return ['order_id' => $this->orderId];
    }
}
use Exception;

class SetDeliverDateToFarAwayException extends Exception
{
    public function __construct()
    {
        parent::__construct(
            'Selecting more than three days into the future is not allowed'
        );
    }
}

and now my method wich creates the error message.

    /**
     * Finalizes the scheduler
     *
     * @return string
     * @throws SetDeliverDateToFarAwayException|Throwable
     */
    public function set(): string
    {
        $today = Carbon::now();
        $deliver = new Carbon();
        $deliver->year($this->year ?? $today->year);
        $deliver->month($this->month ?? $today->month);
        $deliver->day($this->day ?? $today->day);
        $deliver->hour($this->hour ?? $today->hour);
        $deliver->minute($this->minute ?? $today->minute);

        #Mail gun can max schedule mail for 3 days in the future. So we throw an Exception if the date is to big.
        throw_if($deliver->diffInHours($today) > 72, new SetDeliverDateToFarAwayException());
        return Mail::schedule($deliver->toDateTimeString());
    }

CodePudding user response:

To get the exception log message use it like this -

    try {

    } catch(Exception $e) { 
        Log::info(json_encode($e->getMessage()));
    }
  • Related