500 server error when saving Symfony entity - php

I need to couple my application with its database. To do this, I've generated an entity with doctrine:generate:entity. It's produced an entity with appropriate annotations for mapping. I've also used doctrine:schema:update --force to actually create the schema on the database server, which I can confirm it has done with phpMyAdmin.
In my controller I'm trying to simply insert a row like so:
public function testAction() {
$file = new File();
$file->setTest('A Foo Bar');
$em = $this->getDoctrine()->getManager();
$em->persist($file);
$em->flush();
return new JsonResponse(array('foo' => 'bar'));
}
The entity only has one field called test which is string and of length 255. When I request this URL through an AJAX request in my application, it throws back a very uninformative 500 Internal Server Error:
Oops! An Error Occurred
The server returned a "500 Internal Server Error".
Something is broken. Please e-mail us at [email] and let us know what you were doing when this error occurred. We will fix it as soon
as possible. Sorry for any inconvenience caused.
The PHP error logs also don't have any error information. This controller action does work if I remove the database manipulation stuff. The application is also running in the dev environment.
Is there any way I can get a more descriptive error message to at least tell me what's wrong?

This is a default error page that you get in production. You can customize it - http://symfony.com/doc/current/cookbook/controller/error_pages.html
You can catch and read an error creating ExceptionListener - http://symfony.com/doc/current/cookbook/event_dispatcher/event_listener.html
Also you can switch to dev environment to show error text and log.
If you just want dev logs but prod environment, you can copy contents of monolog section app/config/config_dev.yml to app/config/config_prod.yml.

If anyone here comes across this issue and is lost, the cause in my case was that I had specified a new #ORM\ManyToOne relationship and was persisting instead of merging the entity.
This in the past has returned a valid error, but in this case the php script was not handling it at all.

Related

Laravel DB Max Connections error throws twice in single GET request

i have a proyect in production made with Laravel 5.4 on AWS, with EC2 and RDS (with autoscaling).
In a normal day our current configuration doesn't have a problem handling a certain amount of users, but sometimes this number of user grows up enough to start generating this DB Max Connections error [1040], even tho we have autoscaling configured to avoid this (i think that the replica is taking enough time to start while we still have some users trying to access).
So, in the Handler.php file we put this code to show a custom page informing the issue to the user (and not just the generic woops!)
if ($e instanceof \PDOException) {
Log::error('Data Base Exception');
$errCode = $e->getCode();
switch ($errCode) {
case 1040:
return response()->view("errors.database", []);
break;
default:
return response()->view("errors.500", [], 500);
break;
}
}
The problem is that apparently laravel is opening more than 1 connection at the same time even this is only a single GET request (it happens to any request on the proyect), so the Handler.php is reporting it twice. Here is a look at the log file generated when throwing this exception.
[2018-10-11 14:04:09] production.ERROR: Data Base Exception
[2018-10-11 14:04:09] production.ERROR: Data Base Exception
I have tested this on my local enviroment, setting the max_connections attribute from mysql to 1
set global max_connections = 1;
This throws the exception as intented, but the HTML page with the information of the problem appears also twice, just like the log.
html with error to the user
Curious thing: when i set the max_connections atributte to 2, the exception is not throwed and laravel process the request normally.
EDIT: it works in this case because i didn't considered that i was using DBeaver to access the database. But the problem of throwing the exception twice persist
The question is: what is laravel doing that need 2 conections even when is just 1 user trying to access? Or maybe this is something related with some kind of reconnection attempt?

Shopware customer import error: The EntityManager is closed

While importing bulk customer into Shopware only the first row from the CSV imported then throws the error
"The EntityManager is closed".
If I try with only single data it imports the customer but also throws the same error "The EntityManager is closed".
Checked the core_production_date.log and importexport.log in shopware/var/log/ no log there.
Also checked Configureation->logfile, nothing there too.
How can I get the actual error log why it's happening? Please let me know if anybody can help.
Shopware version is 5.2.27
Thanks.
The EntityManager is closed happens when the Database Context of the request was closed due to some SQL Exception.
In my project this happened while using the Resource API of Shopware which might also be used by the Importer. The Resource catches the error so it won't show in the logs. The entity manager is closed though by doctrine because of the SQL error and cannot be reopened in the same request. So any call after that will end up with the "EntityManager is closed" message.
It helps if you find a way to run the import in console where the error will be at least shown as a console log. You can also have a look at the Resource itself to see what kind of data might be wrong or missing.
You can use try..catch and reset the EntityManager in the catch clause, if it's closed (you should extend you API Class from ), eg:
try {
... you code ...
} catch (\Exception $e) {
if (!$this->getManager()->isOpen()) {
$this->resetEntityManager();
}
...
}

Symfony 3 exceptions without error 500

Is possible in symfony 3 to generate exception without internal server error?
I want do something action with this exception (add to databases) but do not stop execute application.
I assume what you want to do is not simply catch an exception, but handle (in your case: log) an uncatched exception.
This is a common scenario and is therefore explained in the cookbook. Basically, you create an event listener class which you register as a service for the “kernel.event_listener” event.
I was struggling with this as well because I was generating custom built exceptions, but no matter what I did Symfony would return an http status of 500. I was handling errors in a controlled fashion, and just needed to notify the user, which was more of a status 200 response since it was a message to the user.
Anyways I found that this didn't work:
$event->setResponse(new Response(json_encode($returnArray), 200));
But if I added a header it works, Symfony looks for this header later and respects it. Without the header Symfony just assigns a 500 if you use an /Exception instead of an /HttpException
$event->setResponse(new Response(json_encode($returnArray), 200, array('X-Status-Code' => 200)));
I'm still new to this exception thing, so let me know if something I'm doing is wrong, but that header fixed my problems.

Laravel/Sentry Eloquent\User::__toString() must not throw and exception

Having a weird issue. I have a portal I have developed which up until today has been working good in both the prod and dev environments. Today after running a composer update everything works great on dev environment but when I pushed it to production one of my pages stopped working. The page allows me to pull up a user account and modify certain fields(pretty straight forward).
As an example/test I have created a test function in the controller to spit out a specific users information:
public function getTest(){
$user = Sentry::findUserByLogin('XXXXX');
echo $user;
}
When I run this function on the dev side it shows all the information its suppose to. When on the production side I get this error:
production.ERROR: 500 - Method Cartalyst\Sentry\Users\Eloquent\User::__toString() must not throw an exception # /employees/admin/test
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Method Cartalyst\Sentry\Users\Eloquent\User::__toString() must not throw an exception' in E:\sites\yaya.com\portal\app\src\employees\controllers\admin.php:0
Stack trace:
[internal function]: Illuminate\Exception\Handler->handleShutdown()
{main} [] []
I have not modified anything inside of Sentry or Eloquent.
Any ideas on what would cause this error? On the production side if I do a var_dump(user) it wont throw the error and I can see everything inside the protected fields. Or if I do echo $user->username it also works just fine. Problem is I need to return the user information as well as the groups the user is in to my JS to display it on my screen depending on the drop down selected for the user.
Finally figured it out! Not sure what happened but I started comparing rows of data in the database and found a few discrepancies. Pulled up the design view and sure enough a couple fields were different on production then my dev enviroment. Instead of "datetime" they were set to "smalldatetime" not sure what would have caused that but changed it to "datetime" and it all started working.
Thanks for the help Werewolf!
The most general case when this error is produced is mistype, when, f.e. instead of
{{ $user->id }}
Someone types
{{ $user }}
So error clearly says that method toString was called.

Best possible PHP error class

I am looking for some coding ideas on the following task I am trying to achive.
I have a list of Error Numbers, Description, and User Friendly Description in a document.
Ex:
Error Number, Description, User Friendly Description
-----------------------------------------------------
1, Internal Error, "An Internal Error has occurred. Please try again later".
2, Delete Failed, "Unable to delete an Entry. Please try later".
I want to write a PHP class to store all the above in such a fashion that I can access them later with ease when an error occurs in the code..
Ex: If my code received an error 2, I want to check that error code with the list of error codes in the class, retrieve the description, user friendly description and display it to the user.
I want this to be of minimum overhead. So, don't want to store it in database.
I am using PHP5 with Zend MVC framework. Anybody can help me with the best possible sample code?
Thanks
Write an ini file with the error code and the user friendly text.
write an class which extends Exception which fetches your errorcodes from the ini file. add a method e.g.
public function getUserFriendlyMsg(){}
which returns the string from the ini file.
in your normal code when you have such an error you just need to throw the exception. e.g.
throw new My_Exception('Delete failed',2);
in your e.g. controller:
try{
// your code
}catch(My_Exception $e){
echo $e->getUserFriendlyMsg();
}
Note: you should consider extending your excpetion class to log the failures to a logfile, for this you can introduce servity levels. (see the manual - exception handling)
I like to use a simple custom error handler and custom exception handler that do the following:
If in development mode:
Show the detailed error message
If E_WARNING or worse, output error message into a log file (e.g. using Zend_Log)
If a fatal error, halt execution and show a nice error page with a full backtrace
If in production mode:
Only log error messages
On fatal errors, halt execution and show a nice "an error has occurred" page only.
I like working with errors, so any exception I catch I call a trigger_error() for to do the output and logging.
You can also extend the default Exception class to do the logging and display. You would want to turn any error that occurs into exceptions. Manual errors you would then trigger as exception using throw.
Inspiration:
Kohana's Error Handler (Screenshot here) is the nicest and greatest I've seen to date. It's open source, maybe you can even grab out that part (make sure you read the license first, though.)

Categories