下面列出了org.apache.commons.lang3.exception.ExceptionUtils#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static TemplateError fromException(
Exception ex,
int lineNumber,
int startPosition
) {
return new TemplateError(
ErrorType.FATAL,
ErrorReason.EXCEPTION,
ErrorItem.OTHER,
ExceptionUtils.getMessage(ex),
null,
lineNumber,
startPosition,
ex
);
}
public static JobLog exception(JobExecution execution, JobLogLevel level, String message, Throwable e) {
JobLog jobLog = message(execution, level, message);
jobLog.stackTrace = ExceptionUtils.getStackTrace(e);
jobLog.rootCause = ExceptionUtils.getMessage(ExceptionUtils.getRootCause(e));
if (StringUtils.isEmpty(jobLog.rootCause)) {
jobLog.rootCause = ExceptionUtils.getMessage(e);
}
if (StringUtils.isEmpty(jobLog.rootCause)) {
jobLog.rootCause = "no message";
}
return jobLog;
}
public static TemplateError fromException(Exception ex) {
int lineNumber = -1;
int startPosition = -1;
if (ex instanceof InterpretException) {
lineNumber = ((InterpretException) ex).getLineNumber();
startPosition = ((InterpretException) ex).getStartPosition();
}
return new TemplateError(
ErrorType.FATAL,
ErrorReason.EXCEPTION,
ErrorItem.OTHER,
ExceptionUtils.getMessage(ex),
null,
lineNumber,
startPosition,
ex,
BasicTemplateErrorCategory.UNKNOWN,
ImmutableMap.of()
);
}
protected static Stream<Arguments> createArguments(String fileName,
Function<Map<String, String>, List<Arguments>> extractArguments, int limit) {
try {
//The files loaded here are a trimmed down version of the vectors tests https://github.com/nemtech/test-vectors
String resourceName = "vectors/" + fileName;
URL url = AbstractVectorTester.class.getClassLoader().getResource(resourceName);
Assertions.assertNotNull(url, "Vector test not found: " + resourceName);
ObjectMapper objectMapper = new ObjectMapper();
// Change this to just load the first 'limit' objects from the json array file.
List<Map<String, String>> list = objectMapper
.readValue(url, new TypeReference<List<Map<String, String>>>() {
});
//Not all the tests can be run every time as it would be slow.
//It may be good to shuffle the list so different vectors are tested each run.
return list.stream().limit(limit).map(extractArguments::apply)
.flatMap(List::stream)
.filter(Objects::nonNull);
} catch (Exception e) {
throw new IllegalArgumentException(
"Arguments could not be generated: for file name " + fileName + ". Exception: "
+ ExceptionUtils
.getMessage(e), e);
}
}
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
try {
Response response = ctx.next(requestSpec, responseSpec);
ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
Object obj = yamlReader.readValue(response.getBody().asString(), Object.class);
ObjectMapper jsonWriter = new ObjectMapper();
String json = jsonWriter.writeValueAsString(obj);
ResponseBuilder builder = new ResponseBuilder();
builder.clone(response);
builder.setBody(json);
builder.setContentType(ContentType.JSON);
return builder.build();
}
catch (Exception e) {
throw new IllegalStateException("Failed to convert the request: " + ExceptionUtils.getMessage(e), e);
}
}
@Override
public void intercept(Invocation inv) {
inv.getController().setAttr("setting", Constant.SETTING);
String errMsg = null;
try {
inv.invoke();
} catch (Exception e) {
log.error(e.getMessage(), e);
errMsg = ExceptionUtils.getMessage(e);
}
// 返回异常信息
if (StringUtils.notEmpty(errMsg)) {
String requestType = inv.getController().getRequest().getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(requestType) || StringUtils.notEmpty(inv.getController().getPara("xmlHttpRequest"))) {
Ret ret = Ret.create().set("state", "error").set("msg", errMsg);
inv.getController().render(new JsonRender(ret).forIE());
} else {
inv.getController().setAttr("errorMsg", errMsg);
inv.getController().render(Constant.VIEW_PATH + "/common/500.ftl");
}
}
}
public static ValidationResult exceptionToValidationResult(Exception ex) {
String errorMessage = ExceptionUtils.getMessage(ex);
if (errorMessage.isEmpty()) {
// If still no error message, we use the class name to report the error
// this should really never happen, but we keep this to prevent loosing error information
errorMessage = ex.getClass().getName();
}
return new ValidationResult(ValidationResult.Result.ERROR, errorMessage);
}
@Override
public TransactionFactory<?> mapToFactoryFromDto(Object transactionInfoDTO) {
try {
Validate.notNull(transactionInfoDTO, "transactionInfoDTO must not be null");
return resolveMapper(transactionInfoDTO).mapToFactoryFromDto(transactionInfoDTO);
} catch (Exception e) {
throw new IllegalArgumentException(
"Unknown error mapping transaction: " + ExceptionUtils.getMessage(e) + "\n" + jsonHelper
.prettyPrint(transactionInfoDTO), e);
}
}
/**
* @param httpClient the http client instance.
* @param url of the host
* @param namespaceRepository the namespace repository used to resolve alias.
*/
public ListenerVertx(HttpClient httpClient, String url, NamespaceRepository namespaceRepository) {
super(new JsonHelperJackson2(JsonHelperJackson2.configureMapper(Json.mapper)),
namespaceRepository);
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Parameter '" + url +
"' is not a valid URL. " + ExceptionUtils.getMessage(e));
}
this.httpClient = httpClient;
this.transactionMapper = new GeneralTransactionMapper(getJsonHelper());
}
public Config() {
try (InputStream inputStream = getConfigInputStream()) {
if (inputStream == null) {
throw new IOException(CONFIG_JSON + " not found");
}
this.config = new JsonObject(IOUtils.toString(inputStream));
} catch (IOException e) {
throw new IllegalStateException("Config file could not be loaded. " + ExceptionUtils.getMessage(e), e);
}
}
/**
* Generates a byte array containing random data.
*
* @param numBytes The number of bytes to generate.
* @return A byte array containing random data.
*/
public static byte[] generateRandomBytes(int numBytes) {
try {
byte[] bytes = new byte[numBytes]; // the array to be filled in with random bytes
new SecureRandom().nextBytes(bytes);
return bytes;
} catch (Exception e) {
throw new IllegalIdentifierException(ExceptionUtils.getMessage(e), e);
}
}
/**
* Converts an hex back to an byte array.
*
* @param hexString the hex string input
* @return the byte array.
*/
public static byte[] fromHexToBytes(String hexString) {
final Hex codec = new Hex();
try {
return codec.decode(StringEncoder.getBytes(hexString));
} catch (DecoderException e) {
throw new IllegalArgumentException(
hexString + " could not be decoded. " + ExceptionUtils
.getMessage(e), e);
}
}
/**
* @param httpClient the ok http client
* @param url nis host
* @param gson gson's gson.
* @param namespaceRepository the namespace repository used to resolve alias.
*/
public ListenerOkHttp(OkHttpClient httpClient, String url, Gson gson, NamespaceRepository namespaceRepository) {
super(new JsonHelperGson(gson), namespaceRepository);
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(
"Parameter '" + url + "' is not a valid URL. " + ExceptionUtils.getMessage(e));
}
this.httpClient = httpClient;
this.transactionMapper = new GeneralTransactionMapper(getJsonHelper());
}
private static IllegalArgumentException handleException(Exception e, String extraMessage) {
String message = ExceptionUtils.getMessage(e);
if (StringUtils.isNotBlank(extraMessage)) {
message += ". " + extraMessage;
}
return new IllegalArgumentException(message, e);
}
@Override
public TransactionFactory<?> mapToFactoryFromDto(Object transactionInfoDTO) {
try {
Validate.notNull(transactionInfoDTO, "transactionInfoDTO must not be null");
return resolveMapper(transactionInfoDTO).mapToFactoryFromDto(transactionInfoDTO);
} catch (Exception e) {
throw new IllegalArgumentException(
"Unknown error mapping transaction: " + ExceptionUtils.getMessage(e) + "\n" + jsonHelper
.prettyPrint(transactionInfoDTO), e);
}
}
public static String loadResource(String resourceName) {
String resName = "json/" + resourceName;
try (InputStream resourceAsStream = TestHelperOkHttp.class.getClassLoader()
.getResourceAsStream(resName)) {
return IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new IllegalStateException(
"Cannot open resource " + resourceName + ". Error: " + ExceptionUtils.getMessage(e),
e);
}
}
public static TemplateError fromSyntaxError(InterpretException ex) {
return new TemplateError(
ErrorType.FATAL,
ErrorReason.SYNTAX_ERROR,
ErrorItem.OTHER,
ExceptionUtils.getMessage(ex),
null,
ex.getLineNumber(),
ex.getStartPosition(),
ex
);
}
public AsyncHttpJoinConverterContext(AsyncHttpJoinConverter converter, SO outputSchema, DI input, Request<RQ> request) {
this.future = new CompletableFuture();
this.converter = converter;
this.callback = new Callback<RP>() {
@Override
public void onSuccess(RP result) {
try {
ResponseStatus status = AsyncHttpJoinConverterContext.this.converter.responseHandler.handleResponse(request, result);
switch (status.getType()) {
case OK:
AsyncHttpJoinConverterContext.this.onSuccess(request.getRawRequest(), status, outputSchema, input);
break;
case CLIENT_ERROR:
log.error ("Http converter client error with request {}", request.getRawRequest());
AsyncHttpJoinConverterContext.this.onSuccess(request.getRawRequest(), status, outputSchema, input);
break;
case SERVER_ERROR:
// Server side error. Retry
log.error ("Http converter server error with request {}", request.getRawRequest());
throw new DataConversionException(request.getRawRequest() + " send failed due to server error");
default:
throw new DataConversionException(request.getRawRequest() + " Should not reach here");
}
} catch (Exception e) {
log.error ("Http converter exception {} with request {}", e.toString(), request.getRawRequest());
AsyncHttpJoinConverterContext.this.future.completeExceptionally(e);
}
}
@SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION",
justification = "CompletableFuture will replace null value with NIL")
@Override
public void onFailure(Throwable throwable) {
String errorMsg = ExceptionUtils.getMessage(throwable);
log.error ("Http converter on failure with request {} and throwable {}", request.getRawRequest(), errorMsg);
if (skipFailedRecord) {
AsyncHttpJoinConverterContext.this.future.complete( null);
} else {
AsyncHttpJoinConverterContext.this.future.completeExceptionally(throwable);
}
}
};
}
/**
* 拼装 短异常类名: 异常信息.
*
* 与Throwable.toString()相比使用了短类名
*
* @see ExceptionUtils#getMessage(Throwable)
*/
public static String toStringWithShortName(@Nullable Throwable t) {
return ExceptionUtils.getMessage(t);
}
/**
* 拼装 短异常类名: 异常信息.
*
* 与Throwable.toString()相比使用了短类名
*
* @see ExceptionUtils#getMessage(Throwable)
*/
public static String toStringWithShortName(@Nullable Throwable t) {
return ExceptionUtils.getMessage(t);
}