Skip to content

Commit 36cb947

Browse files
committed
Add tools to simplify exceptions
1 parent 6a5e7f7 commit 36cb947

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/ParallelProcessingTools.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ using Logging: @logmsg, LogLevel, Info, Debug
1717

1818
using Parameters: @with_kw
1919

20+
include("exceptions.jl")
2021
include("fileio.jl")
2122
include("threadsafe.jl")
2223
include("threadlocal.jl")

src/exceptions.jl

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# This file is a part of ParallelProcessingTools.jl, licensed under the MIT License (MIT).
2+
3+
"""
4+
ParallelProcessingTools.original_exception(err)
5+
6+
Replaces `TaskFailedException`s and `RemoteException`s with the underlying
7+
exception that originated within the task or on the remote process.
8+
"""
9+
function original_exception end
10+
11+
original_exception(err) = err
12+
original_exception(err::CompositeException) = CompositeException(original_exception.(err.exceptions))
13+
original_exception(err::TaskFailedException) = err.task.result
14+
original_exception(err::RemoteException) = err.captured.ex
15+
16+
17+
"""
18+
ParallelProcessingTools.onlyfirst_exception(err)
19+
20+
Replaces `CompositeException`s with their first exception.
21+
22+
Also employs `original_exception` if `simplify` is `true`.
23+
"""
24+
function onlyfirst_exception end
25+
26+
onlyfirst_exception(err) = err
27+
onlyfirst_exception(err::CompositeException) = first(err.exceptions)
28+
29+
30+
"""
31+
@userfriendly_exceptions expr
32+
33+
Transforms exceptions originating from `expr` into more user-friendly ones.
34+
35+
If multiple exceptions originate from parallel code in `expr`, only one
36+
is rethrown, and `TaskFailedException`s and `RemoteException`s are replaced
37+
by the original exceptions that caused them.
38+
39+
See [`original_exception`] and [`onlyfirst_exception`](@ref).
40+
"""
41+
macro userfriendly_exceptions(expr)
42+
quote
43+
try
44+
$(esc(expr))
45+
catch err
46+
rethrow(original_exception(onlyfirst_exception(err)))
47+
end
48+
end
49+
end
50+
export @userfriendly_exceptions

0 commit comments

Comments
 (0)