Doctrine returns different responses array/object - php

I have two Doctrine queries like so:
FetchBookRepository:
public function fetchBook($id)
{
try {
$book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
->find($id);
var_dump($book);die();
} catch (\Exception $ex) {
$this->em->close();
throw new QueryException('003', 502);
}
return $book;
}
FetchAllBooksRepository:
public function allBooks()
{
try {
$book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
->findAll();
var_dump($book);die();
} catch (\Exception $ex) {
$this->em->close();
throw new QueryException('003', 502);
}
return $book;
}
They both work as expected, but when i closely investigate the data returned I noticed that FetchBookRepository returns Object and FetchAllBooksRepository returns array of Objects.
Why is this happening what does the return depend on and is there a way to standardise the return...?

Related

Laravel create custom exception with parameters & return as JSON

I want to throw a custom exception if the variable is null and return it as JSON.
I've tried like this:
Controller
try {
$check_api_key = $attendance_libraries->check_api_key($this->request);
if ($check_api_key == null) {
throw new NullException(false, 'API Key Not Found', null, 500);
}
} catch (NullException $e) {
return $e;
} catch (\Exception $e) {
// do something else
}
Custom Exception
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\Response;
class NullException extends Exception
{
public $is_success;
public $message;
public $code;
public $data;
public function __construct($is_success, $message, $code, $data = null, Exception $previous = NULL)
{
$this->is_success = $is_success;
$this->message = $message;
$this->code = $code;
$this->data = $data;
}
public function render()
{
return response()->json([
'success' => $this->is_success,
'message' => $this->message,
'data' => $this->data,
], $this->code);
}
}
But when I am trying to test it using postman, the return I got is not the same as I wrote in NullException. It becomes like this:
In your case you are returning the exception as a response instead of throwing it. That's why it's displayed like this.
You could just have to throw the exception without the try/catch:
$check_api_key = $attendance_libraries->check_api_key($this->request);
if ($check_api_key == null) {
throw new NullException(false, 'API Key Not Found', null, 500);
}
The laravel error handler will catch the exception & render it.
EDIT: Or as #miken32 pointed out you could re throw the exception to handle other exceptions:
try {
//...
} catch (NullException $e) {
throw $e;
} catch (// other exceptions) {
}
Instead of Returning the render method from Exception you are returning the Exception. And also you are passing the arguments in wrong order.
Route::get('exception', function () {
try {
$check_api_key = null;
if ($check_api_key == null) {
throw new NullException(
is_success: false,
message: "API Key Not Found",
code: 500
);
}
} catch (NullException $e) {
return $e->render();
} catch (\Exception $e) {
}
});

Laravel handle custom Exceptions

I want to handle custom Exceptions (PDOException, ...)
In App/Exceptions/Handler.php I add the following functions:
public function report(Exception $e)
{
if ($e instanceof \PDOException) {
//$this->renderHttpException($e);
//Doesn't work
}
else
{
parent::report($e);
}
}
public function render($request, Exception $e)
{
if($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
return parent::render($request, $e);
}
}
protected function renderHttpException(HttpException $e)
{
if (view()->exists('errors.'.$e->getStatusCode()))
{
return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode());
}
else
{
//comes later
return null;
}
}
If I have a PDOException I can't handle it, because the PDOException doesn't look like a default Laravel Exception.
I know that it can't work, but I don't know how to make it work.
Here is the Laravel (5.1) Error:
Argument 1 passed to App\Exceptions\Handler::renderHttpException() must be
an instance of
Symfony\Component\HttpKernel\Exception\HttpException, instance of
PDOException given, called in /home/****/Workspace/****/app/Exceptions/Handler.php
on line 37 and defined
The function source is from
mattstauffer.co

Why is my exception thrown from a closure not caught?

I've written a PHPUnit test that checks if an exception is thrown from a closure when a method is invoked. The closure function is passed in as an argument to the method with an exception being thrown from it.
public function testExceptionThrownFromClosure()
{
try {
$this->_externalResourceTemplate->get(
$this->_expectedUrl,
$this->_paramsOne,
function ($anything) {
throw new Some_Exception('message');
}
);
$this->fail("Expected exception has not been found");
} catch (Some_Exception $e) {
var_dump($e->getMessage()); die;
}
}
The code for the get function specified on the ExternalResourceTemplate is
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
}
}
Any ideas why the fail assert statement is called? Can you not catch exceptions thrown from closures in PHP or is there a specific way of dealing with them I don't know about.
For me the exception should just propagate out the return stack, but it doesn't appear to. Is this a bug? FYI I'm running PHP 5.3.3
Thanks for the answers...
Managed to figure out the issue. It looks like the problem is that the try-catch block that's being invoked is the one where the closure is invoked. Which makes sense...
So the code above should be
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
throw new Some_Specific_Exception("Exception is actually caught here");
}
}
So it looks like PHP 5.3.3 doesn't have a bug after all which was mentioned. My mistake.
I cannot reproduce the behavior, my example script
<?php
class Some_Exception extends Exception { }
echo 'php ', phpversion(), "\n";
$foo = new Foo;
$foo->testExceptionThrownFromClosure();
class Foo {
public function __construct() {
$this->_externalResourceTemplate = new Bar();
$this->_expectedUrl = '_expectedUrl';
$this->_paramsOne = '_paramsOne';
}
public function testExceptionThrownFromClosure()
{
try {
$this->_externalResourceTemplate->get(
$this->_expectedUrl,
$this->_paramsOne,
function ($anything) {
throw new Some_Exception('message');
}
);
$this->fail("Expected exception has not been found");
} catch (Some_Exception $e) {
var_dump('my exception handler', $e->getMessage()); die;
}
}
}
class Bar {
public function get($url, $p, $fn) {
$fn(1);
}
}
prints
php 5.4.7
string(20) "my exception handler"
string(7) "message"
as expected

Why Symfony2 dont catch exceptions

i have a repository
class TurnoRepository extends EntityRepository
{
public function findTurnoActivo()
{
$q = $this
->createQueryBuilder('t')
->where('t.activo = :activo')
->setParameter('activo', true)
->getQuery();
return $q->getSingleResult();
}
}
this method throw a NoResultException but if i try to catch in my controller
private function obtenerTurno()
{
$em = $this->getDoctrine()->getEntityManager();
$turno = null;
try {
$turnoActivo = $em->getRepository('MyBundle:Turno')->findTurnoActivo();
} catch (NoResultException $e) {
return false;
}
return $turno;
}
always i get 500 Internal Server Error on my page
Symfony2 code is namespaced so you have to add the correct namespace for the class NoResultException, try using:
catch (\Doctrine\ORM\NoResultException $e)
Note the backslash in front of the Doctrine namespace or import the NoResultException class by using use.
You can use $q->getOneOrNullResult(); if you don't want to catch NoResultException in the controller.

how do I stop further methods in a PHP class?

I am learning OOP with PHP. I am creating a class to extract XML data from a website. My question is how do I stop the given object from executing more methods if there is an error with the first method. For example, I want to send the URL:
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
echo "Missing URL";
}
}
public function secondJob()
{
whatever
}
}
when I write like this:
$map = new GEOCACHE ("");
$map->secondJob("name");
How do I prevent the secondJob method from being executed in that given object without the script terminating?
Throw an Exception in the constructor, therefore the object will never be created
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("URL is Empty");
}
}
You can then do something like this:
try
{
$map = new GEOCACHE ("");
$map->secondJob("name");
}
catch ( Exception $e)
{
die($e->getMessage());
}
Consider using exceptions in order to control the flow of the script. Throw an exception in the constructor, and catch it outside.
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("Missing URL");
}
}
public function secondJob()
{
whatever
}
}
try{
$map = new GEOCACHE ("");
$map->secondJob("name");
}catch($e){
// handle error.
}
Throw an exception from __construct
public function __construct($url)
{
if(null == $url || $url == '')
{
throw new Exception('Your Message');
{
}
then in your code
try
{
$geocache = new Geocache($url);
$geocache->secondJob();
// other stuff
}
catch (exception $e)
{
// logic to perform if the geocode object fails
}

Categories