Handle PHP native error messages/alerts

Asked

Viewed 305 times

3

I have a mini framework to generate my elements, make js/ajax requests and interact with BD Mysql based on some patterns.

I’ve been using it for a long time, but I want to increase it a bit and insert a kind of Debugger into the framework.

A very simple example:

  public function mask( string $mask =  'undefined')
    {
        $this->mask = ' data-input-mask="' . $mask . '" ';
        return $this;
    }

This method lies within the class responsible for mounting the element 'input', and grouping with the other methods the call is made as follows:

$input = new \vidbModel\inputElement();

$field = $input
        ->type('text')
        ->field('cpf')
        ->mask('cpf')
        ->name('cpf')
        ->validator('cpf')
        ->value(null)
        ->input(0);

In this example, if I call the method and insert an array into the initiator ->mask, I will get the following error message:

Fatal error: Uncaught TypeError: Argument 1 passed to vidbModel\inputElement::mask() must be of the type string, array given, called in /opt/lampp/htdocs/VIDB/docs/inputs.php on line 25 and defined in /opt/lampp/htdocs/VIDB/model/inputElement.php:78 Stack trace: #0 /opt/lampp/htdocs/VIDB/docs/inputs.php(25): vidbModel\inputElement->mask(Array) #1 {main} thrown in /opt/lampp/htdocs/VIDB/model/inputElement.php on line 78

What I want to do is this:

Receive this error so that I can treat and bring a friendlier message regarding the error, convert that native message written above into something like:

Error found [0001], an array was passed as parameter to the method Mask(), the entry must be done only with a string, to check an example access: http://sitenothere is/vendor/vidb/Docs/inputs.php

I did some research but I couldn’t find anything on how to do it.

You can handle native PHP errors?

Is there a translation for PHP errors? (Although I wouldn’t be interested in that, just out of curiosity)

  • If you are not using PHP 7, you can use the set_error_handler

  • http://php.net/manual/en/function.set-error-handler.php

1 answer

4


In PHP version 7 and later PHP error handling was implemented in Try, recovering the error with Catch

In this way:

try
{
   // seu código
}
catch (Error $e)
{
    echo "Ocorreu um erro: " . $e->getMessage();
}

If your code inside Try shows above error, PHP will not stop running other blocks of code, so your fatal error becomes an exception.

More news from PHP7 visit Here

Regarding translation, I believe it is not possible in a native way, only with plugins or in the "nail" itself. Since the error messages are created by the team that develops PHP and of course English because it is the most comprehensive language in the world. I see no advantages of translating errors as they are few used, after the block has been programmed.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.