views:

117

answers:

2

when using 3rd part libraries they tend to throw exceptions to the browser and hence kill the script.

eg. if im using doctrine and insert a duplicate record to the database it will throw an exception.

i wonder, what is best practice for handling these exceptions.

should i always do a try...catch?

but doesn't that mean that i will have try...catch all over the script and for every single function/class i use? Or is it just for debugging?

i don't quite get the picture.

Cause if a record already exists in a database, i want to tell the user "Record already exists".

And if i code a library or a function, should i always use "throw new Expcetion($message, $code)" when i want to create an error?

Please shed a light on how one should create/handle exceptions/errors.

Thanks

+1  A: 

The only way to catch these exceptions is to use a try catch block. Or if you don't want the exception to occur in the first place you need to do your due diligence and check if the record already exists before you try to insert the record.

If it feels like you're using this all over the place then maybe you need to create a method that takes care of this for you (Dont Repeat Yourself).

Joe Philllips
i want to know what is best practice. how should i create the class for this? what should that class do? abstract away the try...catch block? how should i pass the function/method to be called?
never_had_a_name
A: 

I don't know Doctrine, but regarding your concrete usage, maybe there is a way to determine if you are facing a duplicate entry, something like :

try { /* Doctrine code here */ } catch (DuplicateEntryException $e) { /* The record already exists */ } catch (Exception $e) { /* Unexpected error handling */ }

Or maybe you have to check if the Exception code equals 1062, which is the MySQL error code for duplicate entries.


Any code that may throw an exception should be in a try/catch block. It is difficult in PHP because you cannot know which method throws an Exception.

You should also have a big try/catch block in your main PHP file that avoids displaying the stack trace to the user, and that logs the cause. Maybe you can use set_exception_handler for this.

mexique1