r/java • u/davidalayachew • Sep 18 '26
I really wish we could add debug information to Exceptions without being forced to wrap-and-throw.
For my development, I commonly write code like this.
public void someMethod(String request) {
try {
someMethodThatThrowsAnException(request);
} catch (final Exception exception) {
throw new IllegalStateException("Request FAIL! request = " + request, exception);
}
}(Ignore the fact that I am catching Exception and not a sharper exception type)
This will produce the following stack trace.
Exception in thread "main" java.lang.IllegalStateException: failed during request
at temp.main(temp.java:13)
Caused by: java.lang.IllegalStateException: Request FAIL! request = REQUEST ABC
at temp.someMethod(temp.java:5)
at temp.main(temp.java:11)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:565)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.execute(SourceLauncher.java:262)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.run(SourceLauncher.java:138)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.main(SourceLauncher.java:76)
Caused by: java.lang.IllegalArgumentException: invalid request
at temp.someMethodThatThrowsAnException(temp.java:18)
at temp.someMethod(temp.java:3)
... 6 moreThis is nice, as I can see what the request was that caused the failure. I have added relevant debug information to whoever receives the exception, making it easier to find and resolve the problem.
However, I don't like that I have to change the exception type. And, due to inheritance, I don't even know for sure what possible exceptions will come down the pipe. Thus, creating an instance of the same exception and throwing that is not usually feasible.
I really wish Exceptions had a way to add debug information to them without changing the type.
Something like this.
public void someMethod(String request) {
try {
someMethodThatThrowsAnException(request);
} catch (final Exception exception) {
exception.addDebugInfo("Request FAIL! request = " + request);
throw exception;
}
}The resulting stack trace would look like this instead.
Exception in thread "main" java.lang.IllegalStateException: failed during request
at temp.main(temp.java:13)
Added debug info: Request FAIL! request = REQUEST ABC
at temp.someMethod(temp.java:5)
at temp.main(temp.java:11)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:565)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.execute(SourceLauncher.java:262)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.run(SourceLauncher.java:138)
at jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher.main(SourceLauncher.java:76)
Caused by: java.lang.IllegalArgumentException: invalid request
at temp.someMethodThatThrowsAnException(temp.java:18)
at temp.someMethod(temp.java:3)
... 6 moreNow, when the exception bubbles up to the catch clause in main, it will still be of type IllegalArgumentException instead of IllegalStateException. I know those aren't ideal types to use here, but I'm just making a point via a poor example.
This new style has allowed us to add our debug info, while allowing the error to retain its type.
Sure, common convention is to add a "richer" exception type, then handle that instead of the lower level ones. And that is good advice -- by changing the Checked Exception type, you have notified all callers that they need to handle this new failure condition. For example, you might add a new Exception type to your Exception hierarchy to denote this new failure condition.
But what if callers don't need to handle this failure condition, and you just want to add more debug info to make solving the problem easier? Does that really justify a whole refactor of all calling classes?
Or other way around, what if your downstream callers DO care about the low level exception type? In that case, changing the exception type forces them to extract the exception they want from your wrapper exception.
The fact is, programs break for all sorts of reasons, and those reasons change frequently. Having to refactor your code every single time a new failure reason pops up that you want to add doesn't feel right.
Here's an example.
In AWS SDK for Java v1, if you attempt to do a PutObject onto S3, but the bucket doesn't exist, the error message will tell you that the bucket doesn't exist, but it doesn't tell you what your attempted bucket name was.
Now, if you trace the logs and/or follow the logic of the code, eventually you will get your answer. But wouldn't it be nice if you could add that to the stack trace while keeping it as an AWS exception?
What are your thoughts?
43
u/brunocborges Sep 18 '26
IMO, use proper exception logging so that you can get the information when this happens. And then, use true debugging (IDEs or jdb itself) to debug errors during development time.
26
u/brian_goetz Sep 18 '26
FWIW, I've wanted this literally since the previous millennium. There is always context on the stack that would be helpful in the event of a failure (especially in testing), that, if there were some easy and unintrusive way to communicate "if the stack gets unwound abruptly, put this data in the exception context", would result in both cleaner code and better error messages. There's even an obvious place to display that information, since the stack trace already prints all the call frames.
Many people here have suggested "you can hack this up yourself" (and you can, and I have done so many times over the decades), but that's not the point. By giving us rigid tools for managing graceful stack unwinding, the programming model discourages us from thinking about how to improve error messages.
14
u/romario77 Sep 18 '26
There is this:
You can add suppressed in Throwable where you could put your context.
4
u/snugar_i Sep 18 '26
You can get some of this by using slf4j's MDC or similar facilities. In your example, you could just attach the request to the MDC somewhere up the stack, and the logger would then dump it together with the exception. Obviously, it only makes sense for some cases.
The AWS S3 bucket/file name not being in the exception is annoying, but in our codebase, we solved that by hiding all calls to S3 inside a custom wrapper. It can then repackage the exception with the additional info. As an added bonus, it's then also trivial to have an in-memory implementation of "S3" for unit tests.
4
u/Dull-Criticism Sep 19 '26
Edit: I finally read past your original post, and through some of the comments. You addressed addSuppressed.
addSuppressed()actually gets you most of what you're asking for:This preserves the original exception type, identity, and stack trace while adding information that will show up in the printed stack trace. So downstream code can still catch the original exception type.
The obvious drawback is semantics: suppressed exceptions are intended to represent secondary exceptions that occurred while another exception was already being handled (the classic example being
close()failing in try-with-resources). Here, no second failure occurred; we're just abusing a suppressed exception as a container for diagnostic context. It also means creating an Exception, including its stack trace, just to carry some text.So it's not quite the
addDebugInfo()API you're proposing, but mechanically it gets surprisingly close.5
u/Thysce Sep 18 '26
Your idea transcends Java, I think. „Amending the exception context“ is a new concept that I have also not seen in any other programming language so far.
Interesting idea for sure. It weakens the abstraction, your code makes, by leaking your implementation detail (the lower level exception). So, for a language that prioritizes correctness (like Java), my first reaction is that it doesn’t fit right.
But on languages that prioritize glue code (eg. most scripting or interpreted languages), it feels more at home, as it lightens the burden on the scriptwriter and abstractions are mostly shallow or weak anyways, as there is little vertical stretch between lowest-level and business-level code.
I will contemplate further and am interested on other educated opinions (unlike the other comments in this thread so far)
4
u/john16384 Sep 18 '26
If it is fatal (basically developer error) then there is a need for a stack trace, but little need to wrap it or add more information.
If it is expected (ie. checked exception) then you want to wrap it anyway when it crosses domain boundaries, as otherwise you'd tie your domain to something internal.
If it is unchecked but not a developer error, then it is a mess already, so might as well use addSurpressed.
2
u/jonathaz Sep 19 '26
I built an observability framework a while back that solves this problem and some others, and used it in quite a few projects. The general idea is to know what any given piece of code is doing at any time, how long it takes, etc. Generally this couples to a thread but doesn’t have to; eg it can couple to a task spread out over many smaller executions that happen in async handlers or executors. The general idea is start a task, attach data about it for context, and end it. The start and end capture timing, collect stats, etc. The natural boundaries to instrument are things like web service entry points, scheduled tasks, database calls, etc. The cool part about the data attached to it is with Java and garbage collection, it doesn’t really cost anything. It just keeps objects alive a little longer, it doesn’t serialize them to strings and write them to disk or send them over a network, etc. So you can attach way more data than you would log.
3
u/I-love-to-eat-banana Sep 18 '26
I have not tried this, but Exception has a [] .getStackTrace() and .setStackTrace([])
So you could in theory add your own StackTraceElement at the start of the array. At that point just write your own Exception that takes the exception and the message and throw that.
so new StackTraceElement("temp", "main_debug_info", "REQUEST ABC", 0);
would produce a hacked StackTrace like:
3
u/haukuri Sep 18 '26
This exists in Python. OP is apparently not the only one who thinks this is a good idea.
BaseException.add_note
2
u/jAnO76 Sep 18 '26
Just throw a new Exception(“debug info”, ex) ?
2
u/rzwitserloot Sep 18 '26
There are a couple of wider issues here, but, to give you some immediate answers:
outputStream.writemethod threw an IOException due to the network going down. It has a suppressed exception: A virtually identical IOException, thrown by theclose()call on it that was triggered by ARM (try-with-resources) /lombok.@Cleanup'.Taking a somewhat wider scope:
The general issue is that exception info actually comes from both sides. It comes from the wider side, and from the detail side. The detail side has the skinny on the actual technical failure - 'this exact API URL was invoked but a 404 was returned', 'the disk is full', 'this DB SQL statement was executed but the db engine threw it back at us with this SQL Exception'. It's what went wrong in all the detail you could possibly want, but it does not contain any context. Often it cannot because the relevant context can be entirely missing. As a trivial example, a webservice ends up making some API call to another internal service, and that fails. Obviously it would be great to know precisely what the API endpoint is that was called, who called it (the authentication info from the call), and what parameters were sent, but often that info is not available to the actual code that ends up throwing.
Thus, one 'side' knows the details, the other 'side' knows the context.
The solution is pretty obvious, I'd say, and it works great for me. You employ a few rules:
throws Exception. This is right. An entrypoint is any place where a framework transfers control to application code.public static void mainis an entrypoint (the only one) for java applications, as an example. And indeed, main can (and should!!) be declared asthrows Exception. You do not want anybody to write generic error handling code more than a single time, and the best place to put generic code is that place that must deal with it anyway (whatever JVM internals ends up callingmain, it obviously can't just ignore an exception thrown by main and core dump or whatever!), and the place that has the context.throws Exceptionis important, because we need info from one end (details) + info from the other end (context) to meet in the middle somehow, and we're going to do that by having the details travel allll the way to the place that has the context, and we must not entice anything in between the two to mess with our exception, remove details, and water down its meaning. Said differently: Carefully prunedthrowsin signature is great for library calls. It's dumb for app code. For e.g. web frameworks, every 'this method is invoked by the web framework to deal with a web request' is an entry point. (doGet, for example, in old timey servlet based stuff).throws Exceptionin the core entrypoint path/entrypoint starters. Yes, often code cannot possibly handle a situation (how is some DB abstraction layer meant to deal with 'the DB is offline'?). A method calledsaveGame()is supposed tothrows IOException(or something more abstract, but a checked exception is appropriate).doGet, the code in the JVM that ends up callingpsv main()) will catch everything, possibly evencatch (Throwable), and will add all that context. Often it is right to actually not rethrow anything: The entrypoint handler is where you answer the question 'okay, an exception occurred and no code was capable of dealing with the issue; a general concept now needs to kick in that logs whatever needs to be logged, sends messages to sysadmins if needed, and adds all context we could possibly need'. Here is where it should go, and usually that means you now log the exception with all details, such as the IP of the requester, the auth info, exact endpoint called, parameters, web method, version of the endpoint called, etc - everything pertinent.If you do that, you don't really run into your situation: This need to 'add context' is done in a single place, and given that it's only written once for your entire project, it no longer feels like an annoying boilerplate ritual.
1
u/AmonDhan Sep 18 '26
You can get the getStackTrace() insert a fake StackTraceElement with extra information into the chain, call setStackTrace() with the altered chain, and re-raise the exception
1
u/Icecoldkilluh Sep 18 '26
Bundling context into exceptions can get gnarly
Ive solved issues like this wrapping entry/ exit points of my code with AOP. Stuffing context into the MDC + pulling it out in the exception handler mechanism
1
u/VincentxH Sep 19 '26
Your problem remains inadequate observability. "What lead to this exception" So use tracing, logging and profiling with a proper observability toolset.
1
u/gnahraf Sep 19 '26
It seems to me the problem is more about how exceptions are logged, less about their idiomatic construction in code.
As a workaround, I'm thinking whether getStackTrace() can be overriden so it drills down into the cause's stack trace?
Alternatively, at the API level, how about if the printStackTrace(..) method drilled down into the cause's stack trace?
1
u/Kautsu-Gamer Sep 19 '26
You do not understand Exceptions at all. They should be handled instead of using as debugging tool.
1
u/Holothuroid Sep 19 '26
Rethrow the same exception type?
3
u/xfel11 Sep 19 '26
Minecraft actually has a comprehensive system for this kind of stuff; the crash reports there are some of the best I’ve ever seen.
3
u/Akthrawn17 Sep 18 '26
If you use IntelliJ, look at the Logpoints feature
1
u/Az4hiel Sep 18 '26
We solved this by introducing a thread local/scoped value "DebugContext" abstraction holding basically a collection of entries (I mean we ended up adding support for nested contests so it's more like a stack of collections). The context is being set up on entry to application logic and cleared on exit (In a proxy/aspect-like fashion - for example in a http request filter). This pattern works extremely well and we use it for logging (context gets logged on each message automatically), reporting errors to sentry (context = tags), propagating correlation ids (if in the context set header for remote call) and a lot of different debugging purposes that I do not remember.
Recently I have learned that it's not our original idea but it's a larger pattern sometimes present in logging frameworks - see MDC (mapped diagnostic context - I like our name better tbh).
Honestly I cannot imagine living without it now - especially after we noticed that if we auto add application input data (like request parameters) to it by default then we barely ever have to worry about missing some context (like in your example). Also almost all the debug-related code can be extracted from the business logic to the application edges (infra layers) which is also very nice.
0
u/maxip89 Sep 18 '26
make a wrap method.
0
u/[deleted] Sep 18 '26
[deleted] — view deleted comment
0
u/[deleted] Sep 18 '26
[deleted] — view deleted comment
0
u/[deleted] Sep 18 '26
[removed] — view removed comment