I have something like this in a Symfony controller:
try {
$entity = $this->getDoctrine()->getRepository(Entity::class)->findOneBy(['uuid' => $uuid]);
} catch(\Exception $ex) {
// die('Invalid uuid'); <- this works
throw $this->createNotFoundException('Resource not found...'); // this doesn't work
}
if(!$campaign) {
// this works if the uuid has a valid format but doesn't exist in db
throw $this->createNotFoundException($this->get('translator')->trans(Utils::NOT_FOUND_STRING));
}
I want to show an error 404 and not a 500 if the user opens a page with an invalid UUID.
The exception is caught, because if I put a die() it works. But with throw $this->createNotFoundException(, I get:
ConversionException
Could not convert database value "55012772-4801-4e26-8..." to Doctrine Type uuid_binary
Related
I'm trying to use Laravel API Resource and handle the error message by sending a specific HTTP code
Here is my code :
public function show($id)
{
try {
return FruitResource::make(Fruit::find($id));
}
catch(Exception $e)
{
throw new HttpException(500, 'My custom error message');
}
}
My try/catch is systematically ignored when I try to access the route.
I am voluntarily accessing an object that is not in the database. I have ErrorException with message Trying to get property 'id' of non-object.
I would like to be able to send my own Exception here, in case the user tries to access data that doesn't exist. And return a json error.
Try this (notice the \ before Exception):
public function show($id)
{
try {
return FruitResource::make(Fruit::find($id));
}
catch(\Exception $e)
{
throw new HttpException(500, 'My custom error message');
}
}
I'm trying to do a very basic exception try catch, but it doesn't catch.
$id =0;
try {
$question = $this->model->find($id); // will not find anything since $id = 0
$question->delete(); // throw an exception
return true;
} catch (\Exception $e) {
dd ('hello'); // should end up here, but no?!?!?
} catch (FatalThrowableError $f) {
echo ("fatal"); // or here... but no.
}
but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.
I have tried
use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;
or simply
Exception;
FatalThrowableError;
Also, having the \Exception $e or Exception $e (with or without ) doesn't change anything.
Note that if I add a line like $foo = 4/0 I get into the Exception section (dd (hello)).
in .env APP_DEBUG=true, APP_LOG_LEVEL=debug
I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.
http://php.net/manual/en/language.errors.php7.php
As the Error hierarchy does not inherit from Exception, code that uses
catch (Exception $e) { ... } blocks to handle uncaught exceptions in
PHP 5 will find that these Errors are not caught by these blocks.
Either a catch (Error $e) { ... } block or a set_exception_handler()
handler is required.
You can, additionally, catch (\Throwable $e) {} to account for both Error and Exception types.
I am trying to use a try/catch block to add in some error handling for a custom WordPress plugin that gets Tweets via the Twitter API.
For testing purposes, I am throwing an exception in my class construct method.
class Twitter_Settings() {
public function __construct() {
throw new \Exception('test');
}
}
then in my plugin file, I am doing:
function twitter_init_settings() {
try {
return new Twitter_Settings();
} catch ( Exception $e ) {
echo $e->getMessage();
}
}
twitter_init_settings();
On the frontend, where I am spitting out $tweets = twitter_feed()->output_feed(); (with a foreach loop afterwards) I am getting an Uncaught Exception error. Oddly, it shows the custom message, 'test', so it must know about my exception, so why is it saying it is uncaught?
Uncaught Exception error happen while an exception is not catched (in try catch statements)
Remove the return statment because the catch might not be reached.
When should I use Exception, InvalidArgumentException or UnexpectedValueException?
I don't know the real different between them as I always used Exception.
Different exceptions just give you more granularity and control over how you catch and handle exceptions.
Consider a class where you are doing many things - e.g. getting input data, validating input data and then saving it somewhere. You might decide that if the wrong or empty arguments are passed to the get() method, you might throw an InvalidArgumentException. When validating, if something is out of the ordinary or doesn't match up you could throw an UnexpectedValueException. If something totally unexpected happens you could throw a standard Exception.
This becomes useful when you are catching, as you can handle different types of exceptions in different ways. For example:
class Example
{
public function get($requiredVar = '')
{
if (empty($requiredVar)) {
throw new InvalidArgumentException('Required var is empty.');
}
$this->validate($requiredVar);
return $this->process($requiredVar);
}
public function validate($var = '')
{
if (strlen($var) !== 12) {
throw new UnexpectedValueException('Var should be 12 characters long.');
}
return true;
}
public function process($var)
{
// ... do something. Assuming it fails, an Exception is thrown
throw new Exception('Something unexpected happened');
}
}
In the above example class, when calling it you could catch multiple types of exceptions like so:
try {
$example = new Example;
$example->get('hello world');
} catch (InvalidArgumentException $e) {
var_dump('You forgot to pass a parameter! Exception: ' . $e->getMessage());
} catch (UnexpectedValueException $e) {
var_dump('The value you passed didn\'t match the schema... Exception: ' . $e->getMessage());
} catch (Exception $e) {
var_dump('Something went wrong... Message: ' . $e->getMessage());
}
In this case you get an UnexpectedValueException like this: string(92) "The value you passed didn't match the schema... Exception: Var should be 12 characters long.".
It should also be noted that these exception classes all end up extending from Exception anyway, so if you don't define special handlers for the InvalidArgumentException or others then they will be caught by Exception catchers anyway. So really, why not use them?
As the title says, I want to get all errors before the redirect. So this is my case:
I have a select for changing databases(identical structure but different data);
So let's say I am here: localhost/user/edit/id/100 (database 1)
on db change, I am redirecting the user to the same page, but we load data from database 2.
If it is not found, I get an error:
"Fatal error: Call to a member function on a non-object ..."
How do I catch the errors before the redirect occurs in order to change the url?
Thanks!
Use try {} catch() {} for catching errors before redirect.
try {
if (/* if error occured */) {
throw new \Exception('Error occured');
}
} catch(\Exception $e) {
// redirect with error occured
}
// redirect without error
In Zend maybe need to use return $redirectObj, I don't know Zend well.
In your case, try to do this:
try {
if ( ! $this->getResponse()) {
throw new Exception('Error occured! Can not get response object');
}
return $this->getResponse()->setRedirect($url);
} catch (Exception $e) {
echo $e->getMessage();
die();
}