Jump to content

catch errors of nested methods


froot
 Share

Recommended Posts

I'm having troubles understanding some basic php…

How can I catch errors of nested methods…

Do I need to check for the 'error' key in the the $result variable manually? Or like make subMethods1 return true/false and check for that in the topMethod's try block? I still want to return what the error was in the subMethod…

class myClass extends WireData {s

    public function topMethod($item) {
        $result = [];
        $result['title'] = $item['title'];
        try {
            if ($item['title'] == 'subMethod1') {
                $array = $this->subMethod1($item);
                $result = $this->mergeArrays($array, $result);
            }
            if ($item['title'] == 'subMethod2') {
                $array = $this->subMethod2($item);
                $result = $this->mergeArrays($array, $result);
            }
        } catch (WireException $e) {
            $result['errors'] = $e;
        }
        return $result;
    }

    protected function subMethod1($item) {
        try {
            $result['foo'] = 'bar';
            $result['foobar'] = 'foobar';
            $result['yada'] = 'blah';
            echo $unKnownVariable; // throws error
            return $result;
        } catch ($e) {
            $result['error'] = $e;
            return $result;
        }
    }

    protected function subMethod2($item) {
        try {
            // ...
        } catch ($e) {
            // ...
        }
    }

    protected function mergeArrays($array, $result) {
        foreach ($array as $key => $value) {
            $result[$key] = $value;
        }
        return $result;
    }

}

 

Link to comment
Share on other sites

OK I it looks like I need to catch the exceptions manually, thus evaluate the return values. Anyways, It's easy to throw an error/exception if you know what can go wrong but I cannot anticipate everything that could go wrong so how to catch any type of error? Can I catch internal server errors?

Link to comment
Share on other sites

On 8/27/2022 at 2:49 PM, fruid said:
} catch ($e) {

You must write: `catch(\Exception $e)` as the object must be an instance of the Exception class or of a subclass (see/mean inheritance here) of the Exception class. 

 

A must read is this following blog post on Microsoft and then come back with questions if still any ??

https://docs.microsoft.com/en-us/archive/blogs/kcwalina/how-to-design-exception-hierarchies

  • Excerpt from Krzysztof Cwalina (software architect) :
Quote

I still get a lot of questions on how to design exception hierarchies, despite several attempts to describe it in talks, the FDG book, and in posts on this blog. Maybe the guidance gets lots in the in the complexities of the full guidance surrounding exception handling or I am a bad communicator. Let me assume the former :-), and so here is one more attempt at describing the guidance in the most succinct way I am capable of

 

Edited by flydev ??
excerpt
  • Like 2
Link to comment
Share on other sites

thanks for the input, I'm a step further now.

Is there a way to catch a PHP Notice? I'd like to stop the code and handle appropriately or at least create a log or get an email if anything goes wrong so I can debug. Because it's quite a work load to anticipate everything that could go wrong and throw exceptions manually…

Right now I can only catch \Exception, \Throwable and WireException I believe.

  • Like 1
Link to comment
Share on other sites

I am on mobile, so short answer. 

You can define your own error handler with `set_error_handler`. (Do not forget to restore the default handler, check the php doc.)

Example:

function send_email_on_notice() { … }
 

set_error_handler("send_email_on_notice", E_NOTICE);

[…]

restore_error_handler()

 

Consider testing the behavior of it if you use it on a try/catch block. 
 

  • Like 2
Link to comment
Share on other sites

The thing is, I need to catch anything that php would echo out because it's an AJAX-response that I would parse in the frontend. If it's anything else than valid JSON, JS crashes and stops. So I either try and catch errors when awaiting the AJAX-response in the frontend or try and catch all errors, exceptions, warnings, notices and whatnot in the backend. I'd say the latter is the more elegant solution cause that way all server related issues would be handled on the server, kind of. I do sent what is caught, if it's of interest to the user, nicely json-encoded to the frontend however, which brings me to my next question.

How can I bail out if an error was thrown manually or thrown automatically by PW of PHP? This doesn't work, there's always a message…

if ($err->getMessage() != '') {
	// send to user
} else {
	// send to me
}

Anything I would throw manually is meant for the user to see, anything else is not but is sent to me via email or logged somewhere. Does that make sense?

Thanks for help!

Link to comment
Share on other sites

What I would do in your scenario is:

1) Catch any \Exception and return a valid JSON with for example: $result = ['success' => false, 'error_msg' => 'Description of the error']; and log the exception original message in your logs

2) To "catch" a notice or warning, do that from a script that analyze a custom Apache ErrorLog and send you a mail on a pattern you would like to receive the mails. Just do not show "errors, mean warning, notice..." but log them into a custom Apache ErrorLog.

3) <- should be the first step, write Test Cases, test your code, and more over, do not upgrade a production code directly, as the most notice and warning you will get once your code is working is from deprecated code (PHP version, ProcessWire, Modules..).

And do not forget that you can handle many scenario, eg., you can catch WireException, CustomException, \Exception. You could read some Ryan's code by opening files that are in the wire\core folder to get some example.

 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...