开发者

Too many try/catch block for PDO

开发者 https://www.devze.com 2023-04-10 13:45 出处:网络
In the controllers class files, most of the method functions include try/catch block something like this:

In the controllers class files, most of the method functions include try/catch block something like this:

 try
   {
      $stmt = $this->prepare($sql);
      $stmt->execute($params);
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
      //foreach() or so on...
   }
   catch (Exception $e)
   {
      //bunch开发者_开发问答 of code...
      //save error into database, etc.
      //error into json and pass to view file
   }

There are a lot of code in the catch block, is there a way to reduce it. Is possible to add "throw exception" in the catch block?


Yes, it is. Try it by yourself. You can always throw a new Exception in a catch block or rethrow the same exception.

try
   {
      // ...
   }
   catch (Exception $e)
   {
      // do whatever you want
      throw new Your_Exception($e->getMessage());
      // or
      throw $e;
   }


I don't know what "bunch of code" is. I'm not sure I believe you. If you have that much going on in a catch block you're doing something wrong.

I'd put this kind of code into an aspect if you have AOP available to you.

"Error into database" might throw its own exception. What happens to that?

The only step that I see here that's necessary is routing to the error view.

What does rethrowing the exception do? It's just passing the buck somewhere else. If all these steps don't need to be done, and all you're doing to rethrowing, then don't catch it at all. Let the exception bubble up to where it's truly handled.


You shouldn't be catching Exception. That's much too general. Catch each specific type of Exception with multiple catch statements on your try block:

try {


} catch(PDOException $err) {

} catch(DomainException $err) {

} 
0

精彩评论

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