Invalid argument exception php

InvalidArgumentException vs UnexpectedValueException

When should I use InvalidArgumentException and when UnexpectedValueException? They look the same to me.

Note that one extends LogicException and the other one extends RuntimeException, so the difference shouldn’t be so subtle IMO.

3 Answers 3

Looking closely at the descriptions on the manual pages:

InvalidArgumentException

Exception thrown if an argument is not of the expected type.

(The description was Exception thrown if an argument does not match with the expected value. until mid-2014, but was changed when PHP 5.6 got introduced)

UnexpectedValueException

Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value[,] not including arithmetic or buffer related errors.

From this, we can conclude that InvalidArgumentException is intended to check types of arguments passed to a function, while UnexpectedValueException is intended to verify values vs valid value sets, possibly during the internal computations of a function (e.g. values returned from other functions).

I guess the largest difference is «argument» vs «value».

For example: say i’ve got a function that utilizes the Twitter-api called: getLastMessageDate($userid) : You pass a (numeric) user-id and it returns the date of the last message of that user as yyyy-mm-dd string.

So, this time I call my function with a (valid) user-id and my function gets the date of the last message of that user. With this date I would like to do something, like some formatting.

Источник

how to throw InvalidArgumentException built-in exceptions in Symfony v2.8/PHP v5.6

This question was answered, but it brought up a question about how to catch the InvalidArgumentException, which I added in the Update section.

In my code, the actual message will be more meaningful

Unlike the PHP Manual’s example showing this throw-exception, Symfony outputs the following error when I load a page that causes the above code to execute on my server:

Please, would someone who has used this exception in their Symfony code, tell me which of the component(s) in the suggested component list or some other component that I should add to my code so it can properly throw the InvalidArgumentException exception?

I’m currently catching a database attempt to insert a duplicate row error as follows:

In the case of the Unique Constraint Violation Exception, I look for it with the ‘Doctrine\DBAL\Exception\UniqueConstraintViolationException’ class name string, but in the USE statement, I have use Doctrine\DBAL\DBALException, but the two are different.

I currently don’t want to handle the InvalidArgumentException, but if I did, is there a class name for it? This exception doesn’t have a corresponding USE statement, so I haven’t found one when I searched for one.

More broadly, how do you determine what class names are used for each exception you want to catch? Is there such a list for Symfony exception handling?

Источник

PHP Exception Handling – InvalidArgumentException

Making our way through our in-depth PHP Exception Handling series, today we’ll go over the InvalidArgumentException in PHP. The InvalidArgumentException should be thrown when an inappropriate argument is passed to a method or function. This can be either due to the actual object data type, or because the data itself is invalid in some way.

The Technical Rundown

Full Code Sample

Below is the full code sample we’ll be using in this article. Feel free to use any or all of the code if you wish to follow along.

When Should You Use It?

There are two scenarios where using InvalidArgumentExceptions might be appropriate. The first is when explicitly changing the strict_types flag, which disables the default coercion from one data type argument to that of the declared type, when possible. That is, if passing a string to an int declared type argument, PHP 7 will attempt to convert the value to an int automatically. With strict_types enabled, this coercion is disabled.

To examine how this all works we have setup a testing ground in our code in which we’ll be creating a few new Book instances, which each have an associated Publisher instance assigned to them:

Calling both these test functions doesn’t produce any problems and the output shows our initial Book instances both have their page count updated to the correct value:

However, now let’s enable strict_types at the top of the file and run these functions again:

As we can see, suddenly we’re producing unexpected TypeErrors because PHP is detecting that the explicitly declared type of int is not being passed.

To test this out we’ll try passing a string as the only parameter:

Calling this function produces an unsurprising TypeError once again:

Does this mean that InvalidArgumentExceptions are never appropriate or can never be used for methods with explicit type declarations of class object types? No, it just means that an InvalidArgumentException should be used based on the data value itself, rather than the data type. For example, let’s look at our last test function:

Note: We could obviously just change the passed value to the result of the ucwords() function, prior to assignment to the name property, but we’re purposely neglecting to do so in this example. Either way, execution of the passInvalidPublisherToPublisher() function throws the InvalidArgumentException we were expecting:

Check out the Airbrake-PHP library, designed to quickly and easily integrate into any PHP project, giving you and your team access to real-time error monitoring and reporting throughout your application’s entire life cycle. With automatic, instantaneous error and exception notifications at your fingertips, you’ll be constantly aware of your application’s health, including any issues that may arise. Best of all, with Airbrake’s robust web dashboard cataloging every error that occurs, you and your team can immediately dive into the exact details of what went wrong, making it easy to quickly recognize and resolve problems.

Monitor Your App Free for 30 Days

Invalid argument exception php. Смотреть фото Invalid argument exception php. Смотреть картинку Invalid argument exception php. Картинка про Invalid argument exception php. Фото Invalid argument exception php

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Slim framework Fatal error: Uncaught exception ‘InvalidArgumentException’ with message ‘Cannot create LogWriter

I recently started using Slim framework. I am currently attempting to authenticate using Middleware. This is the where the middleware is called:

This is where my middleware takes care of the authentication:

I receive this error when I attempt the POST call. Other calls not requiring authentication all work correctly.

Fatal error: Uncaught exception ‘InvalidArgumentException’ with message ‘Cannot create LogWriter. Invalid resource handle.’ in D:\Liftmo\Liftmo.com\api\Slim\LogWriter.php:60 Stack trace: #0 D:\Liftmo\Liftmo.com\api\Slim\Slim.php(191): Slim\LogWriter->__construct(false) #1 D:\Liftmo\Liftmo.com\api\Slim\Helper\Set.php(228): Slim\Slim->Slim(Object(Slim\Helper\Set)) #2 D:\Liftmo\Liftmo.com\api\Slim\Helper\Set.php(88): Slim\Helper\Set->Slim\Helper(Object(Slim\Helper\Set)) #3 D:\Liftmo\Liftmo.com\api\Slim\Helper\Set.php(185): Slim\Helper\Set->get(‘logWriter’) #4 D:\Liftmo\Liftmo.com\api\Slim\Slim.php(196): Slim\Helper\Set->offsetGet(‘logWriter’) #5 D:\Liftmo\Liftmo.com\api\Slim\Helper\Set.php(228): Slim\Slim->Slim(Object(Slim\Helper\Set)) #6 D:\Liftmo\Liftmo.com\api\Slim\Helper\Set.php(88): Slim\Helper\Set->Slim\Helper(Object(Slim\Helper\Set)) #7 D:\Liftmo\Liftmo.com\api\Slim\Slim.php(234): Slim\Helper\Set->get(‘log’) #8 D:\Liftmo\Liftmo.com\api\Slim\Slim.php(402): Slim\Slim->__get(‘log’) in D:\Liftmo\Liftmo.com\api\Slim\LogWriter.php on line 60

I’ve run through the code line by line and it seems the issue lies with the line

I’m pretty confused though because the class was used without issue everywhere else in my code.

I’d really appreciate it if someone could help me out. I took the authentication from HERE. Literally could not find this issue resolved anywhere. Using Google App Engine with Cloud SQL to deploy.

Источник

all. my subject says it all. I’m trying to do a test that actually intentionally makes «Invalid argument supplied for foreach()» happen. I’m trying to get PHPUnit to expect it, but. nope, my tests still come to a screeching halt. The reason: «invalid argument supplied for foreach()» right at the exact point where I’m telling it that it’s going to happen.

At the top of my file I have:

My class declaration starts with:

Here are the lines in the test file:

The error happens on that last line. Shouldn’t the previous two lines be telling PHPUnit, «Hey, bub, I expect there to be an error here, and this is the message you should be getting verbatim»??

We’re using PHP 7.3.4 and PHPUnit 8.3.2.

1 Answer 1

When Testing PHP Errors there three things to be aware of 1) ensure that PHPUnit is converting PHP errors, warnings, and notices to exceptions, 1) ensure that PHP’s error reporting is set appropriately, and 3) use the exceptions that PHPUnit converts the errors, warnings, and notices to.

1) ensure PHPUnit is converting errors, warnings, and notices

By default, PHPUnit converts PHP errors, warnings, and notices that are triggered during the execution of a test to an exception. Using these exceptions, you can, for instance, expect a test to trigger a PHP error as shown in Example 2.12.

2) Ensure PHP’s error reporting is set

PHP’s error_reporting runtime configuration can limit which errors PHPUnit will convert to exceptions. If you are having issues with this feature, be sure PHP is not configured to suppress the type of errors you’re testing.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *