在将应用程序提交到应用程序商店之前如何处理潜在错误 'throws'?

What to do about potential error 'throws' before submitting app to app store?

假设我们有一个即将提交到应用商店的应用...但它包含以下代码:

    try? audioSession.setCategory(AVAudioSessionCategoryAmbient)
        if error != nil {
        // this should never happen
        }

    try? audioSession.setActive(true)
        if error != nil {
        // this should never happen
        }

我们必须 "try" setCategory 方法,因为它 "throws" ...但我不知道为什么它会 throw/fail。

我觉得这会被视为垃圾代码...我应该做的不仅仅是说 "this should never happen," 但如果确实发生了错误,我不知道该怎么办.

This 文档也没有给出任何会出现错误的原因。

我应该制作一个弹出窗口 window 显示 "sorry... we encountered an error while attempting to set the category on the audioSession singleton instance... but the reason for this error is beyond this app's control. Press OK so the app can close. This never happened during app testing... so I have no idea why it happened to you now... must have something to do with your device. Maybe reboot? Better luck next time."

或者我应该 "elegantly handle the error?" 当我不知道潜在的错误 "throws" 是什么,更重要的是不知道它们背后的潜在原因时,我该怎么做。

感谢您的任何建议。 :)

即使这种情况发生的可能性很小,即使您没有适当的方法来处理它(假设该应用程序是基于该功能构建的,如果它不起作用,那么该应用程序将变得毫无用处) - 即便如此,我还是建议在其中放置一些不错的处理代码 - 我相信这比让应用程序崩溃要好。

我可能会要求用户向您报告此问题并提供有关其设置的一些详细信息(毕竟,错误本身至少应包含一条消息,可能会提示您出了什么问题)。

如果应用程序崩溃,我会假设开发人员犯了一些错误。如果弹出窗口试图至少广泛地解释获取音频会话时存在一些问题,我至少会知道开发人员试图对此采取一些措施。

基本上,虽然您无法从错误中恢复,但您至少可以在用户体验方面做一些事情

我看到两个你可以采用的策略。

  • 假设抛出错误的唯一方法是传入无效的类别字符串。由于您的字符串被硬编码为提供的常量之一,因此您可以假设这永远不会发生。在这种情况下,使 try 在抛出时导致致命错误。例如

    try! audioSession.setCategory(AVAudioSessionCategoryAmbient)
    

    do 
    {
        try audioSession.setCategory(AVAudioSessionCategoryAmbient)
    }
    catch
    {
         fatalError("setCategory failed with error: \(error)")
    }
    
  • 假设可能有一些本地原因导致它不起作用。在这种情况下,使用 do ... catch 来捕获错误并将其报告给用户。这不一定发生在调用 audioSession.setCategory 的函数中,您可以选择允许它 throw 并允许调用堆栈中的其他函数抛出,直到您到达可以轻松报告错误。如果达到这一点,请确保中间抛出函数能够通过使用 defercatch 块来清除它们的状态。

如果您确定永远不会发生错误,您可以强制尝试

try! audioSession.setCategory(AVAudioSessionCategoryAmbient)
try! audioSession.setActive(true)