Encapsulates an error code (via the Errors enum) and an optional message. Generally, the optional message is only defined if it adds information over the default message associated with the error code.
| 32 | * code. |
| 33 | */ |
| 34 | public class ApiError { |
| 35 | |
| 36 | private static final int MAX_ERROR_MESSAGE_LENGTH = 2048; |
| 37 | public static final ApiError NONE = Errors.NONE.toApiError(); |
| 38 | |
| 39 | private final Errors error; |
| 40 | private final @Nullable String message; |
| 41 | |
| 42 | public static ApiError fromThrowable(Throwable t) { |
| 43 | Throwable throwableToBeEncoded = Errors.maybeUnwrapException(t); |
| 44 | Errors error = Errors.forException(throwableToBeEncoded); |
| 45 | final String message; |
| 46 | if (Objects.equals(error.message(), throwableToBeEncoded.getMessage())) { |
| 47 | message = null; |
| 48 | } else if (error.code() == Errors.UNKNOWN_SERVER_ERROR.code()) { |
| 49 | // we populate error stack message for UNKNOWN_SERVER_ERROR for easy debugging, |
| 50 | // but we may need to avoid this to not leak sensitive information in the future. |
| 51 | String errorStack = ExceptionUtils.stringifyException(throwableToBeEncoded); |
| 52 | // tailor the error stack to reduce the network cost. |
| 53 | message = |
| 54 | errorStack.length() > MAX_ERROR_MESSAGE_LENGTH |
| 55 | ? errorStack.substring(0, MAX_ERROR_MESSAGE_LENGTH) |
| 56 | : errorStack; |
| 57 | } else { |
| 58 | message = throwableToBeEncoded.getMessage(); |
| 59 | } |
| 60 | return new ApiError(error, message); |
| 61 | } |
| 62 | |
| 63 | public static ApiError fromErrorMessage(ErrorMessage msg) { |
| 64 | Errors code = msg.hasErrorCode() ? Errors.forCode(msg.getErrorCode()) : Errors.NONE; |
| 65 | String message = msg.hasErrorMessage() ? msg.getErrorMessage() : null; |
| 66 | return new ApiError(code, message); |
| 67 | } |
| 68 | |
| 69 | public ApiError(Errors error, @Nullable String message) { |
| 70 | this.error = error; |
| 71 | this.message = message; |
| 72 | } |
| 73 | |
| 74 | public boolean isFailure() { |
| 75 | return !isSuccess(); |
| 76 | } |
| 77 | |
| 78 | public boolean isSuccess() { |
| 79 | return this.error == Errors.NONE; |
| 80 | } |
| 81 | |
| 82 | public Errors error() { |
| 83 | return error; |
| 84 | } |
| 85 | |
| 86 | /** |
| 87 | * Return the associated optional error message or null. |
| 88 | * |
| 89 | * <p>Note: the returned message can be null and is useful for transport to reduce unnecessary |
| 90 | * network cost. |
| 91 | */ |
nothing calls this directly
no test coverage detected