Java Code Examples for org.apache.commons.lang3.exception.ExceptionUtils#getMessage()

The following examples show how to use org.apache.commons.lang3.exception.ExceptionUtils#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComActionInterceptor.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@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");
        }
    }
}
 
Example 2
Source File: TemplateError.java    From jinjava with Apache License 2.0 6 votes vote down vote up
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
  );
}
 
Example 3
Source File: JobLog.java    From quartz-glass with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: YamlToJsonFilter.java    From microprofile-open-api with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 5
Source File: TemplateError.java    From jinjava with Apache License 2.0 6 votes vote down vote up
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()
  );
}
 
Example 6
Source File: AbstractVectorTester.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
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);
    }

}
 
Example 7
Source File: RandomUtils.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 8
Source File: TemplateError.java    From jinjava with Apache License 2.0 5 votes vote down vote up
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
  );
}
 
Example 9
Source File: TestHelperOkHttp.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
 
Example 10
Source File: GeneralTransactionMapper.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 11
Source File: JsonHelperGson.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
private static IllegalArgumentException handleException(Exception e, String extraMessage) {
    String message = ExceptionUtils.getMessage(e);
    if (StringUtils.isNotBlank(extraMessage)) {
        message += ". " + extraMessage;
    }
    return new IllegalArgumentException(message, e);
}
 
Example 12
Source File: ListenerOkHttp.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * @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());
}
 
Example 13
Source File: ConvertUtils.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 14
Source File: Config.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
 
Example 15
Source File: ListenerVertx.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * @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());
}
 
Example 16
Source File: GeneralTransactionMapper.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 17
Source File: SalesforceRuntimeCommon.java    From components with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 18
Source File: AsyncHttpJoinConverter.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
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);
      }
    }
  };
}
 
Example 19
Source File: ExceptionUtil.java    From j360-dubbo-app-all with Apache License 2.0 2 votes vote down vote up
/**
 * 拼装 短异常类名: 异常信息.
 * 
 * 与Throwable.toString()相比使用了短类名
 * 
 * @see ExceptionUtils#getMessage(Throwable)
 */
public static String toStringWithShortName(@Nullable Throwable t) {
	return ExceptionUtils.getMessage(t);
}
 
Example 20
Source File: ExceptionUtil.java    From vjtools with Apache License 2.0 2 votes vote down vote up
/**
 * 拼装 短异常类名: 异常信息.
 * 
 * 与Throwable.toString()相比使用了短类名
 * 
 * @see ExceptionUtils#getMessage(Throwable)
 */
public static String toStringWithShortName(@Nullable Throwable t) {
	return ExceptionUtils.getMessage(t);
}