dtbrd80422 2013-05-13 18:06
浏览 166
已采纳

嵌套多个尝试/捕获 - 是否有更好的方法?

I'm making a signup process that ends with a final script where the majority of the heavy lifting is done, after a user has made payment. These processes include:

  • Updating our sales DB several times
  • Making an external API post
  • Downloading, amending and uploading a file via SFTP
  • Sending confirmation emails

Essentially there's a lot of things to potenatially fail individually, all of which are critical and rely on the previous one working. I don't just want the final method to do all this to be along the lines of

try {
    $Signup->doEverything();
}
catch( Exception $e ) {
    echo "Something went wrong"
}

because that is no use to anybody.

I've ended up with a massive nested list of all these final processes that is now 11 deep - it does work, if one of the processes fails it dies with the correct exception, but seeing this many nests I just assume there should be a better way of handling all these processes.. Is this bad practice? Are there better solutions for dealing with large amounts of critical processes like this?

  • 写回答

2条回答 默认 最新

  • dongshan3806 2013-05-13 18:20
    关注

    You should sub-class the exception class

    i.e.

    class ExceptionOne extends Exception
    {
    
    ...
    
    }
    

    Then you can just have one try/catch block

    i.e.

    try
    {
    
       ... i.e. throw an appropriate exception according to the problem
    
    }
    catch (ExceptionOne ex)
    {
       ...
    }
    catch (ExceptionTwo ex)
    {
       ...
    
    }
    
    etc.
    
    catch (Exception ex)
    {
       ... For a catch all
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)