Skip to content

fix(api): restore business error messages in HTTP responses - #7138

Open
halibobo1205 wants to merge 5 commits into
tronprotocol:release_v4.8.3from
halibobo1205:feature/http-business-error-messages
Open

halibobo1205 wants to merge 5 commits into
tronprotocol:release_v4.8.3from
halibobo1205:feature/http-business-error-messages

Conversation

@halibobo1205

@halibobo1205 halibobo1205 commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Restores selected HTTP error messages that #6954 replaced with internal server error.

  • Adds IllegalStateException, NonUniqueObjectException, ItemNotFoundException, BadItemException, ContractExeException and one more Wallet domain exception to the existing allowlist, and allows every non-blank IllegalArgumentException message instead of only Util.EVENTS_DEPRECATED_MSG. The shared writer matches the exact runtime class and returns non-blank messages without adding an exception-class prefix. Unclassified exceptions, unlisted subclasses, and blank messages from allowlisted types still use internal server error.
  • Returns INVALID JSON body for malformed or non-object bodies handled by the shared JSON parser used by getVisiblePost, packTransaction, broadcasthex, and one other servlet that parsed its body on its own. packTransaction also returns it for an empty body.
  • Reports field-shape errors in packTransaction, such as Field 'raw_data' is not an object or Field 'raw_data' is missing.
  • Returns fixed messages for a missing or unknown contractType in createCommonTransaction instead of repeating the request value.
  • In the existing form-body decoding path, returns INVALID form body when Jetty rejects a percent escape or an invalid UTF-8 sequence.
  • Returns INVALID address when the Base58Check decoder throws IllegalArgumentException in Util.getHexAddress.
  • Returns body size is too big, the limit is <n> for the servlet body-size check and oversized chunked requests caught by the shared error handler. An unsupported request charset caught by that handler returns unsupported charset in Content-Type.

Existing HTTP status codes and response shapes are preserved. There are no gRPC or JSON-RPC behavior changes.

Why are these changes required?

The HTTP error filtering introduced by #6954 also hid messages that clients use to correct a request or understand why a query failed. This PR restores guidance for ambiguous TRC-10 names, missing or mismatched blocks, and missing market orders.

This PR has been tested by:

  • Unit Tests: 488 HTTP and Jetty tests on JDK 17 / aarch64 (./gradlew :framework:test --tests 'org.tron.core.services.http.*' --tests 'org.tron.common.jetty.*')
  • Checkstyle: ./gradlew :framework:checkstyleMain :framework:checkstyleTest

Follow up

Some request decoding failures still return internal server error. They will be converted into InvalidHttpParameterException with fixed messages where the input is parsed:

  • non-numeric query parameters such as num, offset and limit
  • malformed hex field values
  • protobuf decoding failures in broadcasthex after the admission check

Util.getHexAddress still turns Base58 addresses with a wrong length or checksum into an empty address instead of an error. That is left for the same follow-up because changing it turns some responses that succeed today into errors.

Extra details

  • Restored messages from the shared error writer omit the class X : prefix used in 4.8.2.4.
  • triggersmartcontract, triggerconstantcontract, and estimateenergy retain their nested result response. For malformed JSON, the decoded result.message now starts with class org.tron.core.exception.InvalidHttpParameterException : INVALID JSON body where it previously reported org.tron.json.JSONException. For the servlet body-size check, the exception class changes from java.lang.Exception to InvalidHttpParameterException and the size-limit text stays the same. In both cases, result.message is hex-encoded in the HTTP response.
  • The shared error writer still allows non-blank messages from the allowlisted exact types. IllegalArgumentException and IllegalStateException throw sites reachable from HTTP request paths on a healthy node were reviewed before widening the allowlist. An unknown contractType and malformed form-body encoding repeated request text, and both now return fixed messages before reaching Wallet.

@halibobo1205 halibobo1205 added this to the GreatVoyage-v4.8.3 milestone Dec 3, 2026
@halibobo1205 halibobo1205 added the topic:api rpc/http related issue label Dec 3, 2026
BadItemException.class,
ZksnarkException.class,
ContractExeException.class,
IllegalArgumentException.class,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[DISCUSS] Exact-class IAE/ISE pass-through re-exposes server-internal messages

Allowlisting every non-blank IllegalArgumentException / IllegalStateException message re-opens part of the surface that #6954 closed, because these JDK-wide types are also thrown by internal code on HTTP-reachable paths with messages not written for callers. One concrete reachable example: CreateCommonTransactionServlet.java:36 calls ContractType.valueOf(Util.getContractType(contract)), so an unknown contract type now returns No enum constant org.tron.protos.Protocol.Transaction.Contract.ContractType.X verbatim, leaking the internal proto class name. The test changes in this PR acknowledge the wider surface: BroadcastServletTest and GetTransactionListFromPendingServletTest had to switch their mocks from IllegalStateException to RuntimeException because wallet/manager ISE messages would now pass through, and the No enum constant internal.Type.VALUE fail-closed case was removed from UtilProcessErrorTest.

This is still stricter than 4.8.2.4 (no class X : prefix, subclasses and blank messages fail closed), so the direction is fine — but the PR description does not record an audit of which internal IAE/ISE messages become visible again.

Evidence clarity: Confirmed

Suggestion: Confirm the reachable IAE/ISE throw sites were audited and note the conclusion in the PR description; for known internal-detail leaks such as the ContractType.valueOf call in CreateCommonTransactionServlet, catch the IAE at the servlet and rethrow an InvalidHttpParameterException with a fixed caller-facing text.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the ContractType case, changed in 708f7da. The shared handler still allows non-blank messages from these exact types, but createCommonTransaction now checks contractType before calling Wallet and replaces the JDK text with fixed messages: Field 'contractType' is missing for a missing or null value, and invalid contractType: expect a ContractType name for a value that isn't a ContractType name.

JSONArray rawContractArray;
try {
rawData = jsonTransaction.getJSONObject("raw_data");
rawContractArray = rawData.getJSONArray("contract");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] packTransaction still returns internal server error for missing raw_data or empty body (NPE path)

The new try/catch only handles JSONException. When the body is {}, {"raw_data":null}, or empty, no exception of that type is thrown: JSON.parseObject("") returns null (NPE at line 363), and getJSONObject("raw_data") returns null for a missing key (NPE at line 364 on rawData.getJSONArray("contract")). NPE is not allowlisted, so these requests still get internal server error — the exact opaque behavior this PR sets out to fix, on the most common malformed shapes for the broadcast-family endpoints that call packTransaction (broadcasttransaction, gettransactionsignweight, gettransactionapprovedlist, getshieldtransactionhash). The new testPackTransactionReportsMisshapedRawData covers wrong-type fields but not the missing-field case.

Evidence clarity: Confirmed

Suggestion: Add explicit null checks for jsonTransaction, rawData, and rawContractArray and throw InvalidHttpParameterException with a fixed message (e.g. Field 'raw_data' is missing), plus test cases for {}, {"raw_data":null}, and an empty body.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 016dad9. packTransaction now parses the body with Util.parseJsonBody, the helper behind getVisiblePost, so an empty or null body returns INVALID JSON body. A missing or null raw_data returns Field 'raw_data' is missing, and a missing or null raw_data.contract returns Field 'contract' is missing. Errors inside the per-contract loop were already caught, so these were the remaining null dereferences in the transaction's outer structure.

byte[] addressByte = decodeFromBase58Check(address);
byte[] addressByte;
try {
addressByte = decodeFromBase58Check(address);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] getHexAddress: decoder null-return paths still silently produce an empty string

The new catch maps IllegalArgumentException from the Base58Check decoder (invalid base58 characters) to INVALID address, but Commons.decodeFromBase58Check returns null instead of throwing for empty input, wrong length (!= 34), checksum failure, and non-0x41 prefix — and ByteArray.toHexString(null) returns "". So within the same method, an address with an illegal character now yields a clear INVALID address error, while a wrong-length or bad-checksum address (the more common client mistake) silently becomes "" with no error at all, and downstream servlets answer with empty/not-found results. This predates the PR, but the PR rewrites exactly this method for exactly this purpose, and the two failure paths now behave inconsistently. getHexAddress has 20+ query-servlet callers.

Evidence clarity: Confirmed

Suggestion: Also throw InvalidHttpParameterException(INVALID_ADDRESS_MSG) when decodeFromBase58Check returns null; if you prefer to keep this PR minimal, record it explicitly in the Follow up section of the PR description.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that the two failure paths are inconsistent, but I'd keep the existing null-return behaviour out of this PR. When the decoder returns null, as it did in 4.8.2.4, each endpoint handles the resulting empty address with its existing logic. Throwing there would turn some responses that succeed today into errors, which is a behaviour change rather than a restored message. I've added it to Follow up.

if (body.getBytes().length > parameter.getHttpMaxMessageSize()) {
throw new Exception("body size is too big, the limit is "
+ parameter.getHttpMaxMessageSize());
throw new InvalidHttpParameterException(bodySizeTooBigMessage());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] checkBodySize: redundant throws Exception after switching to an unchecked exception

checkBodySize previously threw a checked new Exception(...), which justified throws Exception on the signature. It now throws only InvalidHttpParameterException, which is unchecked (it extends java.security.InvalidParameterException -> IllegalArgumentException), so the throws Exception clause no longer matches the implementation and misleads callers about the real failure contract.

Evidence clarity: Confirmed

Suggestion: Drop throws Exception from the signature; this is source-compatible for all existing callers since they catch Exception broadly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in bcfcdb7.

@@ -76,10 +86,25 @@ public class Util {
private static final String INTERNAL_SERVER_ERROR = "internal server error";
public static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources";
static final String INVALID_ADDRESS_MSG = "INVALID address";

@317787106 317787106 Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD]: clarify that this message also covers empty addresses.

Util.getAddress() uses INVALID_ADDRESS_MSG both when the address is missing or blank (StringUtils.isBlank(addressStr)) and when decoding or validation fails. Could we change the text to "Invalid or empty address" so callers can more easily recognize an omitted or empty address parameter as a possible cause?

Please also update the affected error-message assertions, including AddressQueryServletTestBase.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep INVALID address in this PR. Util.getAddress() already uses this one text for both a missing and an invalid address, and this PR reuses it in Util.getHexAddress() when the Base58 decoder throws. The wording also has precedent: in 4.8.2.4, getreward and getbrokerage returned errors starting with INVALID address, . If we want a separate message for a missing address, I'd rather change it in its own PR so the new text is announced on its own.

return INTERNAL_SERVER_ERROR;
}
return INTERNAL_SERVER_ERROR;
return BUSINESS_ERROR_TYPES.contains(type) ? message : INTERNAL_SERVER_ERROR;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remaining request-side errors still fall back to internal server error

The restored messages are useful, but several client-correctable parsing and validation failures still reach Util.processError() without being translated into a client-facing error.

The shared writer matches the exact runtime class, so adding IllegalArgumentException does not cover subclasses such as NumberFormatException or Jetty's Utf8Appendable.NotUtf8Exception.

Missing handling Example request/input Exception and current behavior Suggested handling
Invalid integer query parameters GET /wallet/getblockbynum?num=abc; similar cases exist for offset, limit, and other numeric parameters Long.parseLong() / Integer.parseInt() throws NumberFormatException, which is not an exact allowlisted type, so the response is {"Error":"internal server error"}. See GetBlockByNumServlet. Catch the parsing failure at the parameter boundary and return a fixed, field-specific message, such as invalid parameter [num]: expect a 64-bit integer.
Invalid hexadecimal field values POST /wallet/getaccountresource with {"address":"zz"}, or POST /wallet/broadcasthex with {"transaction":"zz"} Direct calls to ByteArray.fromHexString() can throw Bouncy Castle's DecoderException. These failures still become internal server error, including on POST paths. See BroadcastHexServlet. Translate the decoding failure into a fixed message appropriate to the field, such as Invalid or empty address or Invalid transaction encoding.
Missing/null transaction structure POST /wallet/broadcasttransaction with an empty body, {}, {"raw_data":null}, {"raw_data":{}}, or {"raw_data":{"contract":null}} packTransaction() dereferences a null jsonTransaction, rawData, or rawContractArray. The new catch (JSONException) does not catch these NullPointerException paths, so they still return internal server error. See Util.packTransaction. Check the required structure before dereferencing it and return fixed errors for an empty body, missing raw_data, or missing raw_data.contract.
Missing/null contractType POST /wallet/createCommonTransaction with {} or {"contractType":null} Util.getContractType() returns null, and ContractType.valueOf(null) throws NullPointerException. This still becomes internal server error. See CreateCommonTransactionServlet. Validate contractType before calling valueOf() and return a fixed message such as Missing contractType. Unknown enum values should also receive a fixed validation message rather than the JDK's internal enum-class detail.
Invalid form-body encoding POST /wallet/getblockbynum with Content-Type: application/x-www-form-urlencoded and body num=%FF or num=% UrlEncoded.decodeUtf8To() throws Utf8Appendable.NotUtf8Exception for invalid UTF-8 or incomplete percent encoding. Although it extends IllegalArgumentException, the exact-class allowlist excludes it, resulting in internal server error. See Util.getJsonString. Translate the form-decoding failure into a fixed message such as INVALID form body.
Invalid protobuf string encoding after admission checking POST /wallet/broadcasthex with {"transaction":"0a075a0512030a01ff"} This is valid hex containing a protobuf Any.type_url with invalid UTF-8. The admission guard scans the wire structure without validating that string's UTF-8, so Transaction.parseFrom(raw) can subsequently throw InvalidProtocolBufferException. That exception reaches the generic writer and becomes internal server error. See BroadcastHexServlet. Catch InvalidProtocolBufferException specifically around request transaction parsing and return a fixed message such as Invalid transaction encoding.

The PR description already lists numeric GET parameters and malformed hex values as follow-ups. These are existing coverage gaps rather than regressions introduced by this PR; the remaining cases should also be handled or explicitly documented as deferred.

For the implementation, please translate these failures locally into InvalidHttpParameterException with fixed client-facing messages. Broadening the shared allowlist to expose all NullPointerException, DecoderException, or InvalidProtocolBufferException messages would also expose unrelated internal failures.

Please cover the corresponding malformed, missing, and null inputs in regression tests, verifying that they receive the intended validation message before wallet processing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed list. Handled in this PR:

  • packTransaction: an empty body and a missing or null raw_data / contract now return fixed messages (016dad9).
  • createCommonTransaction: a missing or unknown contractType now returns a fixed message instead of the JDK enum text (708f7da).
  • Form bodies: form decoding failures now return INVALID form body when Jetty rejects a percent escape or an invalid UTF-8 sequence (8576605).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic:api rpc/http related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants