I am facing a problem with my database models in ZF2, I must have touch something in the application as I am sure it worked before.
Wondering if somebody can read out the problem by the follow error messages I've got.
If more error info is needed I can update this question with the stacks :)
Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/home/xxxxx/domains/xxxx.nl/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:909
Message:
An exception was raised while creating "Application\Model\CelebrityTable"; no instance returned
**Previous exceptions:**
Zend\Db\TableGateway\Exception\RuntimeException
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
Well the exceptions says most of what you need to know.
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
I went to Zend/Db/TableGateway/AbstractTableGateway.php:105 and the following piece of code is there;
if (!is_string($this->table) && !$this->table instanceof TableIdentifier && !is_array($this->table)) {
throw new Exception\RuntimeException('This table object does not have a valid table set.');
}
So your exceptions means. The $this->table is not a string, array or an instanceof Zend\Db\Sql\TableIdentifier
So you probably didn't set the table.
Now I never used the AbstractTableGateway so not sure how to use it in the right context. But I don't see a setTable, or something like a setOptions.
So unless you can show your implementation of your TableGateWay, this is as far as I know.
Note, I looked at zf2.3.3
Related
I am wanting to create a registration verification,
So far I have planned out, that my Users table should have a confirmation_code column, and an confirmed column. The confirmed column has a default value of 0 (boolean false).
I create the new User from registration and assign them a confirmation_code.
I then email them a link to the verify route, which expects this confirmation_code in the query string.
The method which handles the verify request will be checking to see if the query string parameter (confirmation_code) exists.
My question is :
If the confirmation_code is absent, should I use the abort(404) method? Or throw a custom exception?
public function verify($confirmation_code)
{
if ( ! $confirmation_code ) {
// abort(404)?
// or,
// throw new Exception?
}
Some feedback on when to use the abort method would be appreciated too.
It's actually your choice to choose what type of error handling and error logging you implement in your project.
As advice, I will say that using custom exceptions for missing field exceptions. is a better idea. You can read more about a 404 error in the given link:
404 error.
Also refer to laravel documentation for more details regarding error logging.
I am using Laravel 4 for a project I am working on. I need to retrieve the first comment from the post. I use the following code to do so.
$comments = Comment::where('post_id', $post->id)->first();
This successfully retrieves the first comment (I know that because I print_r-ed $comments and it returned all the right information).
However, the following line of code triggers the error __toString() must not throw an exception
<td>{{$comments->content}}</td>
When I print_r-ed that it returned type string, and returned the correct string as well. Why then would it even try to convert $comments->content to type string when it is already a string?
Based off the information you've given and my experience with Laravel I'd bet that the line of code causing the exception is not the line you've put in your question.
<td>{{$comments->content}}</td>
This exception is complaining about the view throwing an exception. If this particular line was the issue you'd get a more descriptive exception about how $comments->content can't be converted into a string. You've also already tested that it is indeed a string.
I'd recommend finding where your "View" object is being echoed to the view and change it like so.
{{ View::make('yourbladefile')->__tostring() }}
This worked for me by providing a more accurate and informative exception. For more info on your exception you should check out Why it's impossible to throw exception from __toString()?
It's what gave me the idea in the first place. I know it's not a perfect answer so please let me know if this works and I'll update my answer if this turns out not be the case. Good luck.
I know that this is an old question, but for future googlers (like me) there is another way to solve that error, and it is independent of your framework:
public function __toString()
{
try {
return (string) $this->attributeToReturn; // If it is possible, return a string value from object.
} catch (Exception $e) {
return get_class($this).'#'.spl_object_hash($this); // If it is not possible, return a preset string to identify instance of object, e.g.
}
}
You can use it with your custom class with no framework, or with an entity in Symfony2/Doctrine... It will work as well.
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.
I'm building a newsletter CMS and I want to loog any errors to a database with information like timestamp, error, userID and function info. What's the best way to do this?
I'm thinking I should build a class that handles the errors and inputs them into a MYsql table using PDO.
pseudo code:
class sbmtErr
{
private $errStrng;
protected function sndErr($err, $usrData, $mthd){
$sndErrPDO = new myPDO;
$this->errStrng = "INSERT INTO errTbl (error, userID, method) VALUES ('".$err."', ".usrData['usrID'].", '".$mthd."')";
$sndErrPDO->sqlQry($errStrng);
}
}
My problem here is I don't know how to isolate the method that threw the error.
Is there a better way to do this?
Thanks.
Extend the exception class. CMSErrorException , when thrown (i.e. On construct) use reflection to find out things like function, line number, etc. how you find the user's id depends on how you keep it.
Then, regardless of what you do when you catch it, you call a method (again from the construct) which logs it into the database.
Careful not to throw these custom exceptions inside of the exception code, as it might cause an infinite loop in case of a database error.
I have been wondering since I stepped into the murky waters of OOP and have written a couple or so of distributed libraries when it is necessary to write my own extension of the exception class.
So far I simply use the built in exception class and it seems to serve me well. Is it necessary, and if so when is it ok, for me to write an exception subclass.
You should extend the Exception class with your own Exception types when you need to differentiate between different types of errors. Throwing an Exception just means something went wrong. You have no idea what went wrong though. Should you abort everything? Is this an expected error? Throwing a UserIsNotAllowedToDoThisException instead means something much more specific. The importance is to differentiate what code can handle what kind of error:
try {
new Foo($bar);
} catch (UserIsNotAllowedToDoThisException $e) {
echo "Sorry, you're not allowed to do this.";
}
This code handles the simple case when something is not allowed. If Foo would throw some other exception, like TheDatabaseJustCrashedAndIsBurningException, you don't want to know about this here, you want some global error handler to handle it. By differentiating what went wrong, it allows you to handle problems appropriately.
OK, here a little more complete example:
First, if you use proper OOP, you need Exceptions to fail object constructions. Without being able to fail object constructions, you're ignoring a large part of OOP: type safety and therefore data integrity. See for example:
class User {
private $name = null;
private $db = null;
public function __construct($name, PDO $db) {
if (strlen($name) < 3) {
throw new InvalidArgumentException('Username too short');
}
$this->name = $name;
$this->db = $db;
$this->db->save($this->name); // very fictional DB call, mind you
}
}
In this example, we see a lot of things:
My User objects have to have a name. Failing to pass a $name argument to the constructor will make PHP fail the whole program.
The username needs to be at least 3 characters long. If it is not, the object cannot be constructed (because an Exception is thrown).
My User objects have to have a valid and working database connection.
Failing to pass the $db argument will make PHP fail the whole program.
Failing to pass a valid PDO instance will make PHP fail the whole program.
I can't pass just anything as the second argument, it needs to be a valid PDO object.
This means if the construction of a PDO instance succeeded, I have a valid database connection. I do not need to worry about or check the validity of my database connection henceforth. That's the same reason I'm constructing a User object; if the construction succeeds, I have a valid user (valid meaning his name is at least 3 characters long). I do not need to check this again. Ever. I only need to type hint for User objects, PHP takes care of the rest.
So, you see the power that OOP + Exceptions gives you. If you have an instance of an object of a certain type, you can be 100% assured that its data is valid. That's a huge step up from passing data arrays around in any halfway complex application.
Now, the above __construct may fail due to two problems: The username being too short, or the database is for whatever reason not working. The PDO object is valid, so the connection was working at the time the object was constructed, but maybe it's gone down in the meantime. In that case, the call to $db->save will throw its own PDOException or a subtype thereof.
try {
$user = new User($_POST['username'], $db);
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
So I'd use the above code to construct a User object. I do not check beforehand whether the username is at least 3 characters long, because this would violate the DRY principle. Instead, I'll just let the constructor worry about it. If the construction fails with an InvalidArgumentException, I know the username was incorrect, so I'll let the user know about that.
What if the database is down though? Then I cannot continue to do anything in my current app. In that case I want to halt my application completely, displaying an HTTP 500 Internal Server Error page. Here's one way to do it:
try {
$user = new User($_POST['username'], $db);
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
} catch (PDOException $e) {
abortEverythingAndShowError500();
}
But this is a bad way. The database may fail at any time anywhere in the application. I do not want to do this check at every point I'm passing a database connection to anything. What I'll do instead is I let the exception bubble up. In fact, it has already bubbled up. The exception was not thrown by new User, it was thrown in a nested function call to $db->save. The Exception has already traveled up at least two layers. So I'll just let it travel up even further, because I have set up my global error handler to deal with PDOExceptions (it's logging the error and displays a nice error page). I do not want to worry about this particular error here. So, here it comes:
Using different types of Exceptions allows me to ignore certain types of errors at certain points in my code and let other parts of my code handle them. If I have an object of a certain type, I do not ever have to question or check or worry about its validity. If it wasn't valid, I wouldn't have an instance of it in the first place. And, if it ever fails to be valid (like a suddenly failing database connection), the object can signal by itself that an error occurred. All I need to do is catch the Exception at the right point (which can be very high up), I do not need to check whether something succeeded or not at every single point in my program. The upshot is less, more robust, better structured code. In this very simple example, I'm only using a generic InvalidArgumentException. In somewhat more complex code with objects that accept many arguments, you'd probably want to differentiate between different types of invalid arguments. Hence you'd make your own Exception subclasses.
Try to replicate this by using only one type of Exception. Try to replicate this using only function calls and return false. You need a lot more code to do so every time you need to make that check. Writing custom exceptions and custom objects is a little more code and apparent complexity upfront, but it saves you a ton of code later and makes things much simpler in the long run. Because anything that shouldn't be (like a user with a too short username) is guaranteed to cause an error of some sort. You don't need to check every time. On the contrary, you only need to worry about at which layer you want to contain the error, not whether you'll find it at all.
And it's really no effort to "write your own Exceptions":
class UserStoppedLovingUsException extends Exception { }
There, you have created your own Exception subclass. You can now throw and catch it at the appropriate points in your code. You don't need to do any more than that. In fact, you have now a formal declaration of the types of things that may go wrong in your app. Doesn't that beat a lot of informal documentation and ifs and elses and return falses?
The built in exception is good enough for almost every case. The only scenario that I could think of where you need another one is when there are more than one exception that can be thrown in a try and you want to do different things depending of which one is thrown. You have to distinguish two exceptions. therefore you need another one.
Only write it when you need it, e.g. to signal an own exception, for example if you code a library and no exception of the existing ones speaks the same.
See
Core PHP Exceptions
Core PHP SPL Exceptions
There are a lot of exceptions already build-in in PHP so for the normal program flow things should be covered exception-wise.
If you're developing a more complex system, like a parser, lexer plus compiler and everything is accessed via one routine/faced for it's API, the parser might want to throw a parser exception, the lexer a lexer exception and the compiler a compiler exception.
It can be useful to be able to differentiate. But I normally stick with the build in exceptions, it's easy to refactor later anyway in case it needs more differentiation.
And since there are namespaces nowadays, this is really freaking easy if you stick to the firsthand Exception class from the beginning ;)
IMHO:
Simply if you enter your own domain.
That is usually indicated when you need additional data to provide in your exception.
So actually you then also have to do you own class to add the additional class members.