Welcome Guest, Not a member yet? Register   Sign In
Implementing mail send on errors
#1

We have a web application used by several clients, and it would be useful if, upon specific errors happening in production environments (I was thinking errors of type critical, alert o emergency, if possible), the system would send us developers a quick email to let us know, and also retain the current behavior of showing an error page. I started by trying a custom exception exception handler (app/Libraries/CustomExceptionHandler.php)

PHP Code:
<?php

namespace App\Libraries;

use 
CodeIgniter\Debug\BaseExceptionHandler;
use 
CodeIgniter\Debug\ExceptionHandlerInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Throwable;

/**
* Extends BaseExceptionHandler to send mail in case of serious app errors
* @package App\Libraries
*/
class CustomExceptionHandler extends BaseExceptionHandler implements ExceptionHandlerInterface
{
    public ?string $viewPath APPPATH 'Views/errors';

    public function handle(
        Throwable $exception,
        RequestInterface $request,
        ResponseInterface $response,
        int $statusCode,
        int $exitCode
    
): void {
        log_message('error'"handling an exception of statusCode $statusCode. ".$exception->getMessage());
        // TODO actually implement sending an email.
        
        $this
->render($exception$statusCode);

        exit($exitCode);
    }



and I configured app/Config/Exceptions.php like
PHP Code:
public function handler(int $statusCodeThrowable $exception): ExceptionHandlerInterface
    
{
        if (in_array($statusCode, [400404500], true)) {
            return new \App\Libraries\CustomExceptionHandler($this);
        }

        if ($exception instanceof PageNotFoundException) {
            return new \App\Libraries\CustomExceptionHandler($this);
        }

        return new ExceptionHandler($this);
    }


With, thus far, just an extra log_message or two to see that it was working. It does work, but what I see in the browser is not the normal exception trace for development or the error page for production, but an error "The error view files were not found. Cannot render exception trace."
What am I missing? I tried leaving $viewPath as null or removing it from my custom class, but the error message about view files remains.
Then I also read that I could add a custom Logger to send mail in the cases I need. What would be the best thing to do in my case?
Best regards,
Reply
#2

(04-11-2024, 12:22 PM)adrianovaroli Wrote: What am I missing?

BaseExceptionHandler:
PHP Code:
protected function render(Throwable $exceptionint $statusCode$viewFile null): void 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB