How to have usefull debugging or error messages from laravel - laravel

I'm a bit new to laravel, but I'm experienced in Php.
In previous works, I set a mecanism that allowed me to be informed when nearly any problem occurred on the server:
I got full stack
precise PHP error messages
for nearly all king of errors
a mail sent to me
So when I began to work with laravel, I tried to do the same things, and achieved:
full stack
a mail sent to me
But I can't have meaningful error in all case. One example:
$store = Store::create(...)
In this line I forget to specify the namespace (\App\Store::create), and I get those error messages:
first:
FatalThrowableError ; Type error: Argument 1 passed to App\Http\Controllers\User::create() must be an instance of Illuminate\Http\Request, array given, called in /var/www/html/laravel/blog/app/Http/Controllers/User.php on line 94
second:
ErrorException ; Trying to get property of non-object in VerifyCsrfToken.php (line 156)
third:
FatalThrowableError ; Type error: Argument 1 passed to Illuminate\Session\Middleware\StartSession::addCookieToResponse() must be an instance of Symfony\Component\HttpFoundation\Response, array given, called in /var/www/html/laravel/blog/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php on line 72
I understand that laravel is a complex framework but I can't figure why it produces this errors, and how I can have more useful errors (as as it is I can only know that "something is bad").
Has someone an idea ?
ยน There is some errors that Php prefers to keep to himself (in its logs) :-)

When you start a new Laravel project, error and exception handling is
already configured for you. The App\Exceptions\Handler class is where
all exceptions triggered by your application are logged and then
rendered back to the user.
https://laravel.com/docs/5.4/errors
I recommend you to dive into the official docs and into your App\Exceptions\Handler.
Maybe you are looking for report and render methods in that class.

I finally cornered the problem and I learned a lot.
I thank for their benevolence #Don't Panic and #Vitalmax !
The error was that I forgot that PHP namespaces are case insensitive: in my post I cleaned a bit the code as I knew that it didn't stick to the code's conventions (a controller's name must begin with a capital letter). Originally my controller name was user and the faulty code was:
$user = User::create(...)
As you can guess PHP believed that I wanted to call user::create (as I have such a method in my controller) and not User::create (as I wanted).
What I learned:
don't alter the code when asking for help
Laravel use a cache system that can get in the way of the debugging (see a question that I asked on laracast's forum )
take more time to read the error message; I know this rule but I keep doing otherwise

Related

Drupal, entity_metadata_wrappers and debugging

For handling entities in Drupal I'm using Entity Metadata Wrappers (the "Drupal way").
It's really easy to start coding and see all the advantages it has... except when you get a fatal error and you are not clear where it comes from.
This is what the database log shows:
EntityMetadataWrapperException: Unknown data property
field_whatever. at EntityStructureWrapper->getPropertyInfo()
(line 335 of
/var/www/html/sites/all/modules/entity/includes/entity.wrapper.inc).
Sadly, many times that "field_whatever" is "nid", "uid" or some very common property, so it's name is spread all over my code, which makes me difficult to get to the origin of the error.
I'm currently doing this:
Write a tiny piece of code and then run to see if something fails.
Using getPropertyInfo when handling entities with "not so common" fields.
Loosing hair.
What is worst is that sometimes the error does not appear when you are coding, but a week later. So it could be anywhere...
Is there any way of handling entity metadata wrapper errors better? Can I get better information in the database log and not just a line? A backtrace maybe?
Thanks.
Well, having the devel module active (just to see the nice krumo message) we can do something like this inside our module:
<?php
set_exception_handler('exception_with_trace');
function exception_with_trace($e)
{
dpm($e->getTrace());
}
That will return the backtrace error of the exception thrown by the entity metadata handler on the next page load (some page in your site where everything is running fine).
Also you can set the exception handler exclusively and more elegant just for some pages or some users with some role... or when some parameter in the url is met, or when in some state of your Drupal site is met (ex. when a bool persistent variable 'exception_with_trace' is true). Even, under certain conditions and control, you can use it in production too.
If the site does not work "at all" you can include it in your settings.php file, but instead of printing the trace, you must write the trace to a file and watch the trace in a different context (not Drupal but some php file).
If exceptions are too long and are causing memory problems then getting the trace as string is also possible. See http://php.net/manual/es/exception.gettraceasstring.php
Hope that helps.

Raising an an exception: string vs custom class

Is there any advantage to do:
ApiTokenExpired = Class.new(StandardError)
...
raise ApiTokenExpired if response.errorCode == 429
over this lazier alternative:
raise 'api token expired' if response.errorCode == 429
considering that this error detection happens only once in the code?
There is an important advantage of custom errors like ApiTokenExpired if you have to handle the error in an specific way somewhere in the call stack.
begin
# ...
rescue ApiTokenExpired => error
# handle the specific error
rescue => error
# default error handling
end
IMO the decision to create custom errors doesn't depend on the size of the project or future maintenance.
Since custom error classes cause an extra effort I don't use it by default. When a special error handling is needed then an error class should be introduced.
With the first one, you can selectively rescue that error by the class when that code is embedded in larger software. You can still do that with the second one using pattern match with the error message string, but in general, you might alter the message format over time due to refactoring (as opposed to unlikelihood of changing the exception class with your first form), and there can also be different exceptions that have a similar message string, both of which can break pattern matching. When you consider future maintenance, the first one is better.
It does if your app is designed to have error handling or plan to in the future(I mean, any successfull system will want that one day, right?), the only thing you can do with a string is read it in a log or display it in an error message, with types you can code all sorts of things in a decoupled fashion.
For example, ApiTokenExpired could maybe be handled with "try again" response since it's an external problem or be handled by the steps necessary to renew the API Token(and if you used a Typed Exception, you can plug it in later!), maybe you want all errors that are considered SEVERE or UNEXPECTED to send the system administrator an e-mail and also store statistics on the frequency of the error, typed exceptions allows you to code in anything you want in terms of what to do when your system is misbehaving.

Why "Missing return statement" is not handled in languages?

Today I was getting introduced to Dart myself. At a point while playing with it, something was going wrong. Later I found that it was nothing but I forgot to put return statement in a function so null was set to the variable that was supposed to get value from that function.
At that point I was thinking, in Java it would be caught as error in the very first place. Why C/C++ or the new Dart don't add this feature? Does this feature slows the code down at a large scale? Or there are any other technical reasons behind this?
Every method returns a value, and if there is no return it is null.
However it looks like this some enhancements could be done in the future. See issue 73 : Missing return statement does not trigger warning or error and issue 13373 : Can get the editor to warn when there is no explicit return for a function returning a type.

Joomla 3.0 generic database error handling

Going from Joomla 2.5 to 3.0 with my extension, I'm struggling with how to do the DB error handling (since GetErrorNum is deprecated, see also Joomla! JDatabase::getErrorNum() is deprecated, use exception handling instead).
The way that seems to be the one to go according to the question linked above, is to add the following code for each db->query() code:
if (!$db->query()) {
throw new Exception($db->getErrorMsg());
}
In my opinion, that makes DB error handling more awkward than it was before. So far, I simply called a checkDBError() function after a DB call, which queried the ErrorNum and handled any possible error accordingly.
That was independent from how the DB query was actually triggered - there are different ways to do that, and different results on an error: $db->loadResult() returns null on error, $db->query() returns false. So there will now be different checks for different DB access types.
Isn't there any generic way to handle this, e.g. a way to tell Joomla to throw some exception on DB problems? Or do I have to write my own wrapper around the DatabaseDriver to achieve that? Or am I maybe missing something obvious?
Or should I just ignore the deprecation warning for now and continue with using getErrorNum()? I'd like to make my extension future-proof, but I also don't want to clutter it too much with awkward error handling logic.
Just found this discussion: https://groups.google.com/forum/#!msg/joomla-dev-general/O-Hp0L6UGcM/XuWLqu2vhzcJ
As I interpret it, there is that deprecation warning, but there is no proper replacement yet anyway...
Unless somebody points out any other proper documentation of how to do it in 3.0, I will keep to the getErrorNum method of doing stuff...
Get getErrorNum() function will solve your problem....
$result = $db->loadResult();
// Check for a database error.
if ($db->getErrorNum())
{
JFactory::getApplication()->enqueueMessage($db->getErrorMsg());
return false;
}

when might magento Mage::getModel('customer/form'); fail?

I have the following two lines of code in within a controller class.
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
I am getting "Fatal error: Call to a member function setFormCode() on a non-object in ..."
on the second of those two lines.
what might cause the first line to return a "non-object" ? (I guess it fails and returns a null but why would this happen ?)
I am not sure if this is relevant but this is happening in a site that uses the Enterprise version of magento (Magento ver. 1.8.0.0).
Look into your exeption.log, you should find some ideas there. It might happen if Mage_Customer module is disabled, you have rewrite for 'customer/form' model, or even file with Mage_Customer_Model_Form class is missing.

Resources