How to catch ParamConverter exceptions in Symfony2? - php

Here is the exception I got:
No result was found for query although at least one row was expected.
I am basically getting that exception when a user id is not found in database.
Here is what my route looks like:
localhost/../user/18
and the code in my controller:
public function showAction(User $user){
// ..
}
I know I can use the kernel event exception to handle this, but is there an easier way to catch an exception generated by the ParamConverter?

In some cases it's useful to throw exception manually if object not found. You can tell action skip throw exception if entity not found by adding default value to param.
Example:
public function showUser(User $user = null) {
if (empty($user)) {
throw new CustomExceptionYouWant();
}
...
}

You can create your user ParamConverter by implementing ParamConverterInterface and inside it, create methods you can use as a custom exception or do other processing.
This a good exemple of what you want to create Custom ParamConverter

Related

Implementation of Exception Handling in Laravel 5.2

I am trying to implement exception handling in my application. For this Laravel framework has its own mechanism to handle the exception using report and render method. But to implement exception I need to track the source from where the exception has been raised e.g. specific page, route etc. For this I need to pass the url to report and render method but unable to do so. What needs to be done in order to implement this in below report and render function.
public function report(Exception $e)
{
parent::report($e);
}
public function render($request, Exception $e)
{
/* Token mismatch Exception handler start */
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return response()->view('errors.sessionExpire', [], 500);
}
/* Token mismatch Exception handler start */
return parent::render($request, $e);
}
As you can see from your own example, you have an instance of Request in the argument list. And Request has all request-specific details like current route, URL and so on.
$request->url(); // Current request URL
$request->fullUrl(); // With query parameters
$request->route(); // Get the route closure for this request path
You can also create your own exception classes that accept as many parameters as you wish!
And the less comfortable way already mentioned – you could go through the exception trace.
You need to use Exception::getTrace
var_dump($e->getTrace());
above line will give you all details regarding exception.
public function report(Exception $e){
echo '<pre>'; // add this line
print_r($e->getTrace()); // add this line
parent::report($e);
}

Unable to use ApiProblemListner in apigility using zf2

I am new in zendframework. I am using apigility for rest services and ApiProblemListner to return the response if any error occures.
I have one function in model and this function just through an exception using php exception to use in catch block
I am using model function as the utility function in controller to catch those Exception. While catching exception I am using as
try{
imageUploade(); // this function in model and throwing exception if any error
}catch(\Exception $e){
return new ApiProblemResponse(new ApiProblem(500 , $e->getMessage()));
}
if imageUploade() throw an exception if the image size is more then I am able to catch the exception in catch block. I tried echo $e->getMessage(); and its printing the exception bt if I use new ApiProblem(500 , $e->getMessage()) it is not retuning the json error response with the 500 message. It is returning nothing. even it is not showing any error.
Seems like it is unable to render the error with this class. I am not sure if any event needs to add.
I have tried to search for documents but unable to find it.
Thanks in advance.
Normally it should work if you return an ApiProblemResponse straight from a controller action.
Are you sure your Api-Problem module is active?
Try once like this:
<?php
Application\Namespace;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
class IndexController
{
/**
* #return ApiProblemResponse
*/
public function indexAction()
{
return new ApiProblemResponse(new ApiProblem(500, 'test'));
}
}
If that doesn't work then I think your Api-Problem module is not running or the exception is never caught.

Laravel. Catch Exception thrown on App::make('foo')->bar()

I have a PriceController that updates the prices of my items. In my app, a Price is a set or PriceSegments (or Rules).
So my PriceController#update does:
foreach (Input::get('price_segment_id') as $price_segment_id)
{
try {
\App::make('BF\Controllers\PriceSegmentController')->update($price_segment_id);
} catch(BF\Exceptions\ValidationException $e) {
$errors[] = $e->get_errors();
}
}
And my PriceSegmentController#update does the update of each segment as follow:
$priceSegment = $this->repository->find($id);
if($priceSegment) {
// UPDATE $priceSegment with Input, etc.
$this->validator->validate($priceSegment->toArray());
$priceSegment->save();
}
If I do the try-catch in PriceSegmentController it works as expected, but I would like to do the try-catch un PriceController in order to collect all the error and being able to inform them all at once.
The problem is the Exception is not catched and I do not know why. I guess is something related with the behaviour of App::make('foo') but I did not figure it out.
Some help please?
Thanks
EDIT: The structure of my code is based on this example: http://www.sitepoint.com/data-validation-laravel-right-way/ and I am using my own Exceptions extending the Exception PHP class
I think the problem occurs because you are using the default validation mechanism in laravel as described here.
What you can do instead is to catch exceptions in PriceSegmentController and:
either wrap them with a custom exception type
or create a custom exception using exceptions you catch in that controller
and throw your custom exception further up in the food chain.
I hope it helps.

Laravel catch exception and add message to a messagebag

I have a repository that throws an exception if it can't find a record in the database. Rather than redirect to another page I just want to display a warning alert as the record is not critical to the page but is an "exceptional event".
It's probably best to demonstrate with code:
// FxRateRepositoy
public function getRate(/** args **/)
{
$rate = FxRate::where(.... //query to get the rate
if (!rate)
throw new NonExistentCurrencyException(//message);
return $rate;
}
In my start/global.php I have a handler:
App::error(function(NonExistentCurrencyException $e)
{
Session::flash('alert', $e->getMessage());
return \\ ??
});
What to return? I must return a response or the exception continue uncaught. I want to continue to the intended page but with the alert flashed in the session. Is this possible without having to use try catch blocks in every place this method is called?
Ass an additional question, assuming this exception may be thrown multiple times in one request, what's the best way to accumulate alert messages and display them? I'm thinking something akin to the validation messageBag. Can I just use the global $errors variable or should I create a new, specific messagebag for this purpose?
The problem is that if you return nothing from App::error Laravel will display it's default error page. On the other side you can't return a response because you don't know what response it should be in the error handler.
I suggest you handle it in the controller itself.
You can catch the exception there and flash the message or don't throw an exception at all:
$rate = FxRate::where(.... //query to get the rate
if (!rate){
Session::flash('alert', 'Whoops');
}
Also the findOrFail() and firstOrFail methods might be of use. They throw an ModelNotFoundException if the query yields no results:
try {
$rate = FxRate::where(....)->firstOrFail()
// and so on
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e){
Session::flash('alert', 'Whoops');
}
As for a messages system, take a look at the laracasts/flash package

Doctrine Record Listener

I have a listener which contains a preSave() method. Is there a way for me to halt doctrine
from calling the save method if a condition fails. Unfortunately I am not allowed to throw an exception. Is there any other way?
My first idea would be to set a flag in the preSave()-method and to check for that flag in the save()-method. But I think skipOperation() is what you are looking for:
public function preSave(Doctrine_Event $event)
{
if (!$condition) {
$event->skipOperation();
}
}

Categories