Skip to content

Commit 088b3e8

Browse files
author
Antonis Lilis
committed
Adds options to supress exception fix
1 parent 5b83410 commit 088b3e8

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

src/main/kotlin/eu/afse/jsonlogic/JsonLogic.kt

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ class JsonLogic {
1010
*
1111
* @param logic the logic as a json encoded string
1212
* @param data the data as a json encoded string
13+
* @param safe if true an exception is returned as false else exceptions are thrown
1314
* @return evaluation result
1415
*/
1516
@JvmOverloads
16-
fun apply(logic: String?, data: String? = null) = evaluate(logic.parse as? Map<*, *>
17-
?: logic, data.parse).toString()
17+
fun apply(logic: String?, data: String? = null, safe: Boolean = true) =
18+
evaluateSafe(logic.parse as? Map<*, *> ?: logic, data.parse, safe).toString()
1819

1920
/**
2021
* Apply logic on data and get a result
@@ -25,9 +26,7 @@ class JsonLogic {
2526
* @return evaluation result
2627
*/
2728
@JvmOverloads
28-
fun apply(logic: Any?, data: Any? = null, safe: Boolean = true) =
29-
if(safe) try { evaluate(logic, data).toString() } catch (e: kotlin.NotImplementedError) { "false" }
30-
else evaluate(logic, data).toString()
29+
fun apply(logic: Any?, data: Any? = null, safe: Boolean = true) = evaluateSafe(logic, data, safe).toString()
3130

3231
/**
3332
* Add new operations http://jsonlogic.com/add_operation.html
@@ -37,6 +36,14 @@ class JsonLogic {
3736
*/
3837
fun addOperation(operator: String, lambda: (List<Any?>?, Any?) -> Any?) = customOperations.put(operator, lambda)
3938

39+
private fun evaluateSafe(logic: Any?, data: Any? = null, safe: Boolean = true) = if (safe) {
40+
try {
41+
evaluate(logic, data)
42+
} catch (e: kotlin.NotImplementedError) {
43+
false
44+
}
45+
} else evaluate(logic, data)
46+
4047
private fun evaluate(logic: Any?, data: Any? = null): Any? {
4148
if (logic !is Map<*, *>) return logic
4249
if (logic.isNullOrEmpty()) return data

src/test/kotlin/eu/afse/jsonlogic/JsonLogicTests.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ class JsonLogicTests {
177177
}
178178

179179
@Test
180-
fun unknownCustomOperation2() {
180+
fun unknownCustomOperationSafe() {
181181
val jsonLogic = JsonLogic()
182182
val result = jsonLogic.apply(mapOf("hello" to listOf(1, 2, 3)), safe = true)
183183
assertEquals("false", result)

0 commit comments

Comments
 (0)