Skip to content

Commit e678e8d

Browse files
Add CombinedException
Useful for combining multiple exceptions into one, example: catching multiple exceptions after different actions and presenting them in the ui as a single combined exception. Co-authored-by: David Allison <62114487+david-allison@users.noreply.github.com>
1 parent a88bd14 commit e678e8d

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Copyright (c) 2025 David Allison <davidallisongithub@gmail.com>
3+
*
4+
* This program is free software; you can redistribute it and/or modify it under
5+
* the terms of the GNU General Public License as published by the Free Software
6+
* Foundation; either version 3 of the License, or (at your option) any later
7+
* version.
8+
*
9+
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
10+
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
11+
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
12+
*
13+
* You should have received a copy of the GNU General Public License along with
14+
* this program. If not, see <http://www.gnu.org/licenses/>.
15+
*/
16+
17+
package com.ichi2.anki.exception
18+
19+
private typealias ExceptionFormatter = (index: Int, ex: Throwable) -> String
20+
21+
/**
22+
* Combines multiple [exceptions] into a single aggregate exception with options to customize the
23+
* message.
24+
* @param messageOverride if not null it will be used as the [message] of this exception
25+
* @param messageFormatter if not null it will be used to format the message of each child
26+
* exception. Not used if messageOverride is set.
27+
*/
28+
class CombinedException(
29+
vararg val exceptions: Throwable,
30+
messageFormatter: ExceptionFormatter? = null,
31+
messageOverride: String? = null,
32+
) : Exception() {
33+
override val message: String =
34+
when {
35+
messageOverride != null -> messageOverride
36+
messageFormatter != null ->
37+
exceptions
38+
.mapIndexed { idx, ex -> messageFormatter(idx, ex) }
39+
.joinToString("\n")
40+
41+
else -> exceptions.joinToString("\n") { it.message ?: it.javaClass.simpleName }
42+
}
43+
44+
companion object {
45+
fun from(values: List<Pair<String, Throwable>>): CombinedException? {
46+
if (values.isEmpty()) return null
47+
return CombinedException(
48+
exceptions = values.map { it.second }.toTypedArray(),
49+
messageOverride = values.joinToString("\n") { it.first },
50+
)
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)