开发者

how to handle exceptions/errors in php?

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.开发者_如何学Go..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


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜