我在微服务体系结构中有一个应用程序。这个应用程序从不同的来源获取数据,并从其他各种应用程序获得许多不同的错误响应。有些异常,如404-找不到的异常可以抛出并返回给最终用户,但是其他异常(糟糕的请求,++)不能也需要通过抛出其他异常来抑制。
然而,我知道这可以通过try-catch处理异常来解决,并控制在这件事上要添加的内容,但是这需要大量的代码。有时我想接受4-5个不同的例外,而其他时候只有1-2个例外.
不管怎样..。我需要帮助做一个高阶函数。我想要一个函数将一个或多个“接受的异常”作为参数(它们是运行时异常),并且只在try-catch中抛出已批准的异常。
这就是我尝试过的,,但似乎没有正确的语法(伪代码atm.)。任何帮助都是非常感谢的。
fun getData() {
return supressExceptions(
NotFoundException::class.java,
ForbiddenException::class.java,
AuthorizationException::class.java) {
service.getData()
}
}
private inline fun <T, X : RuntimeException> supressExceptions(vararg approvedException: Class<X>, block: () -> T): T =
try {
block()
} catch (ex: Exception) {
// Loop through the approved exceptions.
// Throw the approved exception
throw ex
// ELSE: do something else if the exception is not approved.
}发布于 2019-01-23 07:43:58
下面是你要找的东西吗?
private inline fun <T> supressExceptions(vararg approvedException: Class<out RuntimeException>, block: () -> T): T =
try {
block()
} catch (ex: Exception) {
if (approvedException.contains(ex::class.java)) {
// Approved exception
throw ex
}
// ELSE: do something else if the exception is not approved.
else throw Exception("Something else")
}发布于 2019-01-23 07:46:22
这可以通过any来实现。
private inline fun <T, X : RuntimeException> supressExceptions(vararg approvedException: Class<X>,
block: () -> T): T =
try {
block()
} catch (ex: Exception) {
when {
approvedException.any { ex::class.java == it } -> throw ex
else -> {
throw SupressedException(ex)
}
}
}如果至少有一个条目与给定谓词匹配,则any:返回true。
发布于 2019-01-23 09:38:52
正如注释中已经提到的那样:从命名的角度来看,我希望suppressExceptions会接受一个要被抑制的异常的参数。
我想知道您是否确实希望检查抛出的异常是否实际上是给定异常类型的实例,即是否应该批准/抑制给定类型的子类。
在这种情况下,我宁愿使用以下代码:
inline fun <T> suppressAllExceptions(vararg exceptExceptions: Class<out Exception> = emptyArray(),
block: () -> T) = try {
block()
} catch (e: Exception) {
throw if (exceptExceptions.any { it.isInstance(e) }) {
e
} else SuppressedException(e)
}你仍然会像你展示的那样使用它:
suppressAllExceptions {
throw IllegalStateException("i am suppressed soon")
}
suppressAllExceptions(IllegalStateException::class.java,
IllegalArgumentException::class.java) {
throw IllegalStateException("i am not suppressed")
}
class MyIllegalStateException : IllegalStateException()
suppressAllExceptions(IllegalStateException::class.java,
IllegalArgumentException::class.java) {
throw MyIllegalStateException("i am not suppressed neither")
} 我想得越多:为什么你会在不同的地方批准不同类型的例外?我听起来不太对。除了一些定义良好的异常之外,您可能更希望取消所有异常,在这种情况下,您首先不需要这样的泛型函数,而是有一个包含定义良好的列表的抑制函数:
/**
* Suppresses all exceptions except the well-defined ones: [NotFoundException], ...
*/
inline fun <T> suppressExceptions(block: () -> T) = try {
block()
} catch (e: Exception) {
throw when (e) {
is NotFoundException,
is ForbiddenException,
// all the other well-defined non-suppressable types
is AuthorizationException -> e
else -> SuppressedException(e)
}
}https://stackoverflow.com/questions/54321577
复制相似问题