Symfony 3 handling errors - symfony

Is there a way to handle all errors, from my symfony controllers, for example, if I get this error:
In my controller is there a way using try/catch to get this error?. For example:
class SomeClass extends Controller
{
public function doSomethingAction(Request $request){
//do something
try {
//do something
}
catch(\Exception $e){
dump("ERROR:".$e->getMessage()); //<--this is not dumping anithing
}
}
}
I get allways the red screen message in the network call preview:
Instead of something like:
"ERROR: Type error: Argument 1 passed to.....

With PHP 7 you are able to handle PHP errors like TypeErrors from mismatching types (like in your example) as well as exceptions by catching their shared interface Throwable.
You should be careful with this, especially outside controllers, as this could prevent you from seeing unexpected errors which can lead to problems down the line or you not seeing when parts of your application are entirely broken. At the very least you should have proper logging in place.
In summary, you can catch errors along with exception like this:
try {
...
} catch (\Throwable $error) {
...
}

Related

POST 500 Internal Server Error

I'm going mad with this error.
POST
http://localhost:56105/Home/getContactbyId?ConId=%225%22 500 (Internal Server Error)
Hope you'll be able to help me. I need to get Contact data based on ContactId. Following is the relevant code (apologies if I missed something, I'll add if needed):
contactController.js
ContactsApp.controller("contactController", function ($scope, $rootScope, $routeParams, $location, myService) {
function getContactById(id) {
var getting = myService.get_Contact_By_Id(id);
getting.then(function successCallback(response) {
$rootScope.Name = response.data.Name;
}, function errorCallback(response) {
    return "Error";
       });
   }
 function init() {
var contactId = $location.path().split("/")[2];
    console.log(contactId); //this loggs the correct Id
getContactById(contactId);
}
init();
}
myService.js
ContactsApp.service("myService", function ($http) {
this.get_Contact_By_Id = function (ConId) {
console.log(ConId); //this logs the correct id
return $http({
method: 'post',
url: '/Home/getContactById',
params: {
ConId: JSON.stringify(ConId)
}
});
}
}
HomeController.cs
public class HomeController : Controller
{
public string getContactById(int ConId)
{
int id_int = Convert.ToInt32(ConId);
using (ContactsDBEntities contactsData = new ContactsDBEntities())
{
var theOne = contactsData.Contacts.Where(x => x.Id == id_int).FirstOrDefault();
return theOne.Name;
}
}
}
Using JSON.stringify(ConId) returns a quoted string with the ConId number. params expects a simple object with name : value pairs. Simply use
params: {
ConId: ConId
}
When the ConId is sent using stringify(), the Convert.ToInt32(ConId) call will throw an Exception for conversion (expected NUMBER, not 'NUMBER'). You should put some validation after using that conversion, or a try - catch block.
Also it could be a problem with returning FirstOrDefault() if no result is found. You should check also the theOne variable before using it.
You should check the server application log (Application Event Viewer) to see the exception causing the HTTP Error 500.

symfony2 can't catch PDOException

I want to catch PDOException in symfony 2.6, especially ConnectionException.
For instance if I stop my MySQL server I want to catch that exception and return a customised message to the user, but it seem that it's uncatchable in customised kernel.exception listner, and either in try catch block, i don't know if it's a symfony problem or something must be done.
I also tried out to customise error page like said in documentation but usselssly, I seached in web for solution, but I found nothing except something about redefining a controller in frameworkbundle whish is responsable of converting Exception into error page.
But I really don't want to go for that solution since i'm new with symfony.
You can do this by creating an exception listener and catch Pdo exception :
service.yml:
kernel.listener.your_pdo_listener:
class: Acme\AppBundle\EventListener\YourExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onPdoException }
Then the listener class :
YourExceptionListener
UPDATED
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class YourExceptionListener
{
public function onPdoException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof \PDOException || $exception->getPrevious() instanceof \PDOException) {
//now you can do whatever you want with this exception
}
}
}
Snippets from : Catching database exceptions in Symfony2
I have done more test, so the test i made first was making a query to the database, that's why i got pdoexception as first exception but sometime it can be a twig exception as you know twig throw runtime exception if it couldn't contact database but hopefully we can get the previous exception also and this can work with other exceptions which can be thrown after the PDO ones, so hopefully it will work for you as expected so i edited the code to check if previous exception is a PDOException also.

symfony2 kernel intercept my exception

I've a try-catch statement code inside an action of a controller:
public function MyAction(){
...
try{
...
}
catch(MyException $e){
...
}
....
}
But the exception is intercepted by symfony, show me the twig template of exception detected. It means my catch statemant is never executed, right?
Why? (inside the try i'm just calling a method of another object)
What's wrong?
How Can I do symfony execute my own exceptions?
(I think it's really strange, beacuse it's similar the try-catch em->persist/flush)
I've just forgot the use statetament or the full namespace path and so php can't find MyExceptionClass.
resolve as
catch(path\to\MyException $e){...}
or
use path\to\MyException;
....
...
catch(MyException $e){

phpunit fail message for wrong exception thrown

I'm using phpunit for TDD approach. Currently, some tests I've already written fail, because I'm waiting for other people to catch up with my tests. Therefore, I want to print out a failed assertion message for each assertion that fails now, e.g.
$this->assertTrue($now_its_false, '> my friend should fix method X to return Y');
This works for standard assertions, but I can't figure out how to print such message when testing exceptions. For example, I've test a method that should raise an exception, but it doesn't. My code looks like this:
public function testSomethingIncorrect() {
$this->setExpectedException('SomeException');
$object->doSomethingThatShouldRaiseException();
$this->fail('This call should raise exception!');
}
How to print out the test fail message here?
There is no "clear" way to achieve this. You can notice that PHPUnit_Framework_Constraint_Exception doesn't take any description argument.
Anyway you can do it "around".
try {
$object->doSomethingThatShouldRaiseException();
$this->fail('This call should raise exception!');
} catch ('SomeException') {
}

Extending phpunit error message

I want to add log output to all test messages.
$this->assertTrue(FALSE, "This assertion is False.". myLog::GetErrors());
I tried extending the PHPUnit_Framework_TestCase::assertThat function with my appended message, but it doesn't seem to have an effect on it. I know the extended PHPUnit_Framework_TestCase works because I have several helper functions (random string generation) in there as well that I use for testing.
Any other thoughts? Could it be a customer listener?
All of the assertions are static methods from PHPUnit_Framework_Assert and cannot be overridden by a subclass of TestCase. You can define your own assertions that call the originals with an amended message, however.
public static function assertTrue($value, $message='') {
PHPUnit_Framework_Assert::assertTrue($value, $message . myLog::GetErrors());
}
All failed tests call onNotSuccessfulTest() with the exception as the only parameter. You could override this method and in some cases add your log errors to the exception's message. Some of the PHPUnit exceptions provide a second description in addition to the error message contained in the exception.
public function onNotSuccessfulTest(Exception $e) {
if ($e instanceof PHPUnit_Framework_ExpectationFailedException) {
$e->setCustomMessage(implode(PHP_EOL,
array($e->getCustomMessage(), myLog::GetErrors())));
}
parent::onNotSuccessfulTest($e);
}
Update: As Gregory Lo noted in a comment below, setCustomMessage() and getCustomMessage() were removed in PHPUnit 3.6. :(
In recent PHPUnit Versions it is not necessary anymore.
When you specify the error parameter in an $this->assertXXXX() it preceeds PHPUnit's original message.
Screenshot:

Resources