简体   繁体   English

如何正确地在 Kotlin 中快速失败?

[英]How to do a fail fast in Kotlin properly?

I want to fail fast if a specific function is returning null .如果特定函数返回null我想快速失败。 I have no case where default value would make processing meaningful.我不知道默认值会使处理有意义。

This is the snippet:这是片段:

        val entityAttributes = entity.optJSONObject("Attributes") ?: run {
            LOG.error("Could not find 'Attribute' entry in Entity object")
            return
        }

So if entity.optJSONObject("Attributes") returns null (which it does desipite the opt* ) I want to escape from the function scope.因此,如果entity.optJSONObject("Attributes")返回 null (尽管它确实存在opt* ),我想从函数范围中逃脱。

Is the way I did it the proper one?我这样做的方式正确吗? I am fairly new to Kotlin and want to get used to the proper ways of doing these things as early as possible.我对 Kotlin 相当陌生,希望尽早习惯正确的方法来做这些事情。

You can return from the function early like you do above.您可以像上面那样提前从函数中返回。 If your function returns something besides Unit, then you'd have to return some default value.如果您的函数返回除 Unit 之外的其他内容,那么您必须返回一些默认值。

Throwing an exception allows you to exit a function without returning anything, but the exception will crash the program if you don't catch it somewhere.抛出异常允许您在不返回任何内容的情况下退出函数,但如果您没有在某处捕获异常,则该异常将使程序崩溃。 Sometimes this is exactly what you want to happen if the error is something that should never happen, because then you'll catch it during testing and be able to fix it before releasing your application.有时,如果错误是不应该发生的事情,那么这正是您想要发生的,因为那样您将在测试期间捕获它并能够在发布应用程序之前修复它。

Use the global error(cause: Any) function and it will immediately throw an IllegalStateException.使用全局error(cause: Any)函数,它会立即抛出一个 IllegalStateException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM