Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better logging of errors #3748

Merged
merged 6 commits into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 29 additions & 14 deletions eo-runtime/src/main/java/org/eolang/PhSafe.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
package org.eolang;

import EOorg.EOeolang.EOerror;
import java.util.LinkedList;
import java.util.List;

/**
* An object with coordinates (line and position) and a safe
Expand Down Expand Up @@ -197,25 +199,38 @@ private <T> T through(final Action<T> action, final String suffix) {
this.label(suffix)
);
} catch (final Throwable ex) {
final StringBuilder msg = new StringBuilder(0);
final StackTraceElement[] stack = ex.getStackTrace();
if (stack != null && stack.length > 0) {
final StackTraceElement last = stack[0];
msg.append(last.getFileName())
.append(':')
.append(last.getLineNumber())
.append(": ");
}
msg.append(ex.getClass().getSimpleName())
.append(": ")
.append(ex.getMessage());
throw new EOerror.ExError(
new Data.ToPhi(msg.toString()),
this.label(suffix)
new Data.ToPhi(ex.getMessage()),
trace(ex, this.label(suffix))
yegor256 marked this conversation as resolved.
Show resolved Hide resolved
);
}
}

/**
* Take stacktrace from exception.
* @param exp The exception
* @param head The head to add
* @return The stacktrace
*/
private static List<String> trace(final Throwable exp, final String head) {
final StackTraceElement[] stack = exp.getStackTrace();
final List<String> trace = new LinkedList<>();
if (stack != null) {
for (final StackTraceElement elm : stack) {
trace.add(
String.format(
"%s#%s():%d",
elm.getClassName().replaceAll("([a-zA-Z])[^.]*\\.", "$1."),
elm.getMethodName(),
elm.getLineNumber()
)
);
}
}
trace.add(head);
return trace;
}

/**
* The label of the exception.
* @param suffix The suffix to add to the label
Expand Down
6 changes: 1 addition & 5 deletions eo-runtime/src/test/java/org/eolang/PhSafeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,7 @@ public Phi take(final String name) {
"throws correct class"
).enclosure()
).take(String.class),
Matchers.allOf(
Matchers.startsWith("PhSafeTest.java:"),
Matchers.containsString("IllegalArgumentException"),
Matchers.containsString("intentional error")
)
Matchers.equalTo("intentional error")
);
}

Expand Down
Loading