1
votes

I have a question about error reporting in Laravel 8.

According to the documentation, it should be possible to implement custom report() or render() methods in a custom exception.

I have created a custom exception as follows:

class AdminException extends Exception
{
    protected $userId;

    public function __construct($message='', $userId=0) {
        parent::__construct($message);
        $this->setUserId($userId);
    }

    public function getUserId() {
        return $this->userId;
    }

    private function setUserId($userId) {
        return $this->userId = $userId;
    }

    public function report(){
        dd('in custom admin exception report');
    }

    public function render($request){
        dd('in custom admin exception render');
    }
}

The issue is, when I throw this error intentionally from a controller, I am not hitting any of these methods in the exception.

To try and compensate for that problem, I added methods in the Handler.php file as follows:

$this->reportable( function(AdminException $e){
    dd('in reportable method from handler');
});

$this->renderable( function(AdminException $e, $request){
    dd('in renderable method from handler');
});

but neither of these methods are being hit either. Does anyone have experience with custom exceptions in Laravel 8? The documentation is very unclear, how is this meant to work? Should I just use the report() and render() methods of the Handler.php file?

Thanks!

1

1 Answers

1
votes

I am answering this in case anyone else stumbles upon this problem.

After tweeting back and forth with Taylor Otwell himself, I got some clarification on the subject.

When using the Hander.php file in Laravel, you can use the report() method but it is important to call parent::report($e) before doing anything else. Without doing this, the reporting logic will not be hit.

However, the preferred behavior is to not use the report() method in Handler.php but instead to register report or render callbacks in the register() method of Handler.php.

Just to clarify, it is possible to implement the report() method in Handler.php as a fallback but the parent::report($e); method must be called in the report() method.