com.crabshue.commons.exceptions.utils.ExceptionUtils Maven / Gradle / Ivy
package com.crabshue.commons.exceptions.utils;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Utility class to manipulate exceptions.
*/
@Slf4j
public class ExceptionUtils {
private static final int MESSAGE_MAX_LENGTH = 4000;
/**
* Build a message from a {@link Throwable}.
*
* Loop through all the causes and extract the message.
*
*
* @param throwable the throwable.
* @return the message built.
*/
public static String buildMessageFromThrowable(final Throwable throwable) {
final StringBuilder sb = new StringBuilder();
try {
final String message = throwable.getMessage();
sb.append(message);
sb.append("\n");
if (throwable.getCause() != null) {
final String causeMessage = buildMessageFromThrowable(throwable.getCause());
sb.append(causeMessage);
}
} catch (Exception e) {
logger.error("Cannot read exception ", e);
sb.append("something went wrong");
}
return StringUtils.abbreviate(StringUtils.removeEnd(sb.toString(), "\n"), MESSAGE_MAX_LENGTH);
}
/**
* Remove all the stack traces from a {@link Throwable}.
* This is done to prevent issues in the JSON serialization of exceptions.
*
* @param throwable the throwable.
*/
public static void removeStackTraces(final Throwable throwable) {
throwable.setStackTrace(new StackTraceElement[]{});
if (throwable.getCause() != null) {
removeStackTraces(throwable.getCause());
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy