Skip to content

Commit

Permalink
feat(java sdk): define erro code enums (#77)
Browse files Browse the repository at this point in the history
* feat(java sdk): define erro code enums

Signed-off-by: STRRL <im@strrl.dev>

* feat(java sdk): introduce ReddioBusinessException and ReddioServiceException

Signed-off-by: STRRL <im@strrl.dev>

* test(java sdk): append integration test cases

Signed-off-by: STRRL <im@strrl.dev>

* feat(java sdk): new error codes

Signed-off-by: STRRL <im@strrl.dev>

* feat(java sdk): update error codes

Signed-off-by: STRRL <im@strrl.dev>

* test: update test cases for invalid api key

Signed-off-by: STRRL <im@strrl.dev>

---------

Signed-off-by: STRRL <im@strrl.dev>
  • Loading branch information
STRRL authored Mar 1, 2023
1 parent f8af09a commit 7eb74d7
Show file tree
Hide file tree
Showing 19 changed files with 454 additions and 160 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.api.v1.requests.polling;

import com.reddio.ReddioException;
import com.reddio.exception.ReddioException;
import com.reddio.api.v1.requests.UnwrapCompletionExceptionKt;
import com.reddio.api.v1.rest.*;
import lombok.SneakyThrows;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.api.v1.requests.polling;

import com.reddio.ReddioException;
import com.reddio.exception.ReddioException;
import com.reddio.api.v1.requests.UnwrapCompletionExceptionKt;
import com.reddio.api.v1.rest.*;
import lombok.SneakyThrows;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reddio.ReddioException;
import com.reddio.exception.ReddioBusinessException;
import com.reddio.exception.ReddioErrorCode;
import com.reddio.exception.ReddioException;
import com.reddio.exception.ReddioServiceException;
import okhttp3.*;
import okhttp3.internal.http2.ErrorCode;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
Expand Down Expand Up @@ -335,10 +339,10 @@ public static <T> ResponseWrapper<T> ensureSuccess(ResponseWrapper<T> responseWr
if ("OK".equals(responseWrapper.getStatus())) {
return responseWrapper;
}
throw new ReddioException("response status is not OK, status: " + responseWrapper.getStatus() + ", error: " + responseWrapper.error + ", messages: " + String.join(",", messages));
throw new ReddioBusinessException(responseWrapper.getStatus(), responseWrapper.getError(), ReddioErrorCode.fromCode(responseWrapper.getErrorCode()), responseWrapper);
}

private static class ToCompletableFutureCallback<T> implements Callback {
static class ToCompletableFutureCallback<T> implements Callback {
private final CompletableFuture<T> future;
private final TypeReference<T> typeReference;

Expand All @@ -348,23 +352,35 @@ public ToCompletableFutureCallback(CompletableFuture<T> future, TypeReference<T>
}

@Override
public void onFailure(@NotNull Call call, IOException e) {
public void onFailure(Call call, IOException e) {
this.future.completeExceptionally(e);
}

@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
public void onResponse(Call call, Response response) {
try {
String responseBodyAsString = response.body() != null ? response.body().string() : "";
ReddioErrorCode errCode = tryExtractErrorCode(responseBodyAsString);
if (!response.isSuccessful()) {
this.future.completeExceptionally(new IOException("response is not successful, code: " + response.code()));
this.future.completeExceptionally(new ReddioServiceException("reddio service not respond as sucessful", response.code(), errCode, responseBodyAsString));
return;
}
String jsonString = Objects.requireNonNull(response.body()).string();
this.future.complete(objectMapper.readValue(jsonString, typeReference));
this.future.complete(objectMapper.readValue(responseBodyAsString, typeReference));
} catch (Throwable e) {
this.future.completeExceptionally(e);
}
}

public static ReddioErrorCode tryExtractErrorCode(String responseJsonString) {
try {
final ResponseWrapper<?> model = objectMapper.readValue(responseJsonString, new TypeReference<ResponseWrapper<?>>() {
});
return ReddioErrorCode.fromCode(model.getErrorCode());
} catch (Throwable e) {
// TODO: debug log
return null;
}
}
}

public static final class ReddioUAInterceptor implements Interceptor {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
@AllArgsConstructor(staticName = "of")
public class GetNonceResponse {
@JsonProperty("nonce")
public long nonce;
public Long nonce;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@
@AllArgsConstructor(staticName = "of")
public class ResponseWrapper<T> {
@JsonProperty("status")
public String status;
private String status;

@JsonProperty("error")
public String error;
private String error;

@JsonProperty("error_code")
private Integer errorCode;

@JsonProperty("data")
public T data;
private T data;

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public class SequenceRecord {
public RecordType recordType;

@JsonProperty("sequence_id")
public long sequenceId;
public Long sequenceId;

@JsonProperty("stark_key")
public String starkKey;
Expand All @@ -55,7 +55,7 @@ public class SequenceRecord {
public String resp;

@JsonProperty("time")
public long time;
public Long time;

@JsonProperty("to")
public String to;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ public class TransferMessage {
@JsonProperty("amount")
public String amount;
@JsonProperty("nonce")
public long nonce;
public Long nonce;
@JsonProperty("vault_id")
public String vaultId;
@JsonProperty("receiver")
public String receiver;
@JsonProperty("receiver_vault_id")
public String receiverVaultId;
@JsonProperty("expiration_timestamp")
public long expirationTimestamp;
public Long expirationTimestamp;
@JsonProperty("signature")
public Signature signature;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
public class TransferResponse {

@JsonProperty("sequence_id")
public long sequenceId;
public Long sequenceId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.reddio.exception;

import com.reddio.api.v1.rest.ResponseWrapper;
import jnr.x86asm.RID;
import lombok.Getter;


/**
* ReddioBusinessException represents the business exception that return by the reddio service.
*/
public class ReddioBusinessException extends ReddioException {
private static final long serialVersionUID = -6477748788283734748L;

/**
* The status in the response.
*/
@Getter
private final String status;

/**
* Error message.
*/
@Getter
private final String error;

/**
* Error code as enum, might be null if the error code is not recognized.
* <p/>
* You could still get the error code from raw response {@link #getResponse()}.
*/
@Getter
private final ReddioErrorCode errorCode;

/**
* Raw response from the reddio service.
*/
@Getter
private final ResponseWrapper<?> response;

public ReddioBusinessException(String status, String error, ReddioErrorCode errorCode, ResponseWrapper<?> response) {
this.status = status;
this.error = error;
this.errorCode = errorCode;
this.response = response;
}

@Override
public String getMessage() {
return String.format("reddio business failure, status: %s, error: %s, error code: %s", status, error, errorCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.reddio.exception;

import lombok.Getter;

public enum ReddioErrorCode {
Success(0),
StarkKeyMissing(1),
AmountInvalid(2),
TokenIDMissing(3),
TokenIDParseFailed(4),
NOSuchAccountID(5),
NoSuchAssetID(6),
NoMintableToken(7),
InsufficientAvailable(8),
InsufficientFrozen(9),
AddSequenceFailed(10),
FailedToGenerateNonce(11),
OrderFormatError(12),
DuplicateTransactionError(13),
FullWithdrawError(14),
NotSuchContract(15),
FailedToGenerateVaultID(16),
CancelOrderWrongOwner(17),
StarkKeyInvalid(18),
InvalidParam(19),
OrderConditionalCanceled(20),
FOKAndIOCCanceled(21),
TokenIDInvalid(22),
MintAmountInvalid(23),
DuplicateOrderInfoError(24),
NotSuchToken(25),
CanceledOrder(26),
ContractAddressMissing(27),
NoSuchContractType(28),
FailedToParseUint(29),
CommandToEventFailed(30),
EventNotMatch(31),
InvalidAPIKey(32),
InvalidOwnerOfContract(33),
FailedToVerifyParams(400),
FailedToJSONUnmarshal(401),
SystemError(500);

ReddioErrorCode(int code) {
this.code = code;
}

@Getter
private final int code;

public static ReddioErrorCode fromCode(Integer code) {
if (code == null) {
return null;
}
for (ReddioErrorCode errorCode : ReddioErrorCode.values()) {
if (errorCode.getCode() == code) {
return errorCode;
}
}
return null;
}

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package com.reddio;
package com.reddio.exception;

/**
*
*/
public class ReddioException extends RuntimeException {

public ReddioException() {
super();
}

public ReddioException(String message) {
super(message);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.reddio.exception;

import lombok.Getter;

/**
* ReddioServiceException represents the exception when the reddio service not respond successfully.
*
* @author strrl
*/
public class ReddioServiceException extends ReddioException {
public ReddioServiceException(String description, int httpStatusCode, ReddioErrorCode errorCode, String responseBody) {
this.description = description;
this.httpStatusCode = httpStatusCode;
this.errorCode = errorCode;
this.responseBody = responseBody;
}

private static final long serialVersionUID = 1205765559865993637L;

/**
* Description of the exception.
*/
@Getter
private final String description;

/**
* Http status code.
*/
@Getter
private final int httpStatusCode;

/**
* Error code as enum, might be null if the error code is not recognized.
*/
@Getter
private final ReddioErrorCode errorCode;

/**
* The raw response body as string.
*/
@Getter
private final String responseBody;


@Override
public String getMessage() {
return String.format("reddio service not respond service, description: %s, http status code: %d, error code: %s, response body: %s", description, httpStatusCode, errorCode, responseBody);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package com.reddio.api.v1

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.reddio.ReddioException
import com.reddio.exception.ReddioException
import com.reddio.abi.Deposits
import com.reddio.abi.Withdrawals
import com.reddio.api.v1.rest.GetAssetIdMessage
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.api.v1

import com.reddio.ReddioException
import com.reddio.exception.ReddioException
import com.reddio.api.v1.rest.*
import com.reddio.sign.PaymentSign
import kotlinx.coroutines.delay
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.api.v1

import com.reddio.ReddioException
import com.reddio.exception.ReddioException
import com.reddio.api.v1.rest.GetRecordResponse

class TransferFailedException(override val message: String?, val record: GetRecordResponse) : ReddioException(message) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.api.v1.requests

import com.reddio.ReddioException
import com.reddio.exception.ReddioException
import com.reddio.api.v1.QuantizedHelper
import com.reddio.api.v1.ReddioClient
import com.reddio.api.v1.StarkExSigner
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.reddio.misc

import com.reddio.ReddioException
import com.reddio.exception.ReddioException
import com.reddio.api.v1.StarkExSigner
import com.reddio.api.v1.requests.ReddioCancelOrderApi
import com.reddio.api.v1.requests.ReddioTransferToApi
Expand All @@ -9,7 +9,6 @@ import com.reddio.api.v1.rest.GetBalancesResponse.BalanceRecord
import kotlinx.coroutines.future.await
import kotlinx.coroutines.runBlocking
import java.util.stream.Collectors
import kotlin.streams.toList

/**
* BulkAssetsTransfer is a helper class which would transfer **all the assets** from sender to receiver as best effort.
Expand Down
Loading

0 comments on commit 7eb74d7

Please sign in to comment.