@error turns a Java exception into a typed GraphQL error appended to a service payload’s errors: list, instead of failing the resolver. The reference page covers signature and constraints. This recipe addresses three operational questions the directive raises: when to use a union of @error types vs a single error type for the carrier, how message: resolves between the handler’s description: and the exception’s own message, and what the synthesised path: slot actually contains at runtime.
Carrier shapes: union vs single type
The carrier is the errors: field on the payload type. Two shapes work:
# backed by com.example.FilmPayload via its @service producer's return type
type FilmPayload {
film: Film
errors: [FilmError]
}
union FilmError = YearOutOfRange | NotAllowed | DbError
vs:
# backed by com.example.FilmPayload via its @service producer's return type
type FilmPayload {
film: Film
errors: [SimpleError]
}
type SimpleError @error(handlers: [...]) {
path: [String!]!
message: String!
}
The classifier treats both the same way: ErrorChannel.mappedErrorTypes is a List<ErrorType>, populated with the union members in the union case and a one-element list in the single-type case. The runtime claim (ErrorRouterClassGenerator.buildClaimMethod) walks that list once per thrown exception; cardinality of the list does not change the matching algorithm.
The choice is semantic, not structural:
-
Union fits when distinct error classes carry distinct fields.
YearOutOfRangemight want avalidRange: Stringslot;DbErrormight want aconstraint: String. Each member is its own object type with its own SDL field set, and graphql-java’s type resolver dispatches on the runtime instance. Use a union when clients should branch on__typenameto read shape-specific fields. -
Single type fits when every error has the same shape and only the
message:(andpath:) varies. The handler list on the single@errortype can still cover many distinct exception classes — the union pattern is for distinct result shapes, not distinct handlers.
The rewrite doesn’t pick a side, and in neither case does it construct your payload class: the producing field returns the value your service handed back on success, and on a claimed throw the errors arrive at errors: while every other field reads null, or [] for a non-null list (see @mutation for the rule). The payload class needs no errors slot. This holds for a @service field at a root and below one: a child @service whose payload has an errors field catches into it the same way, as long as it returns a single payload rather than a list of them. A child @service declared on such a payload reads its keys off the value the payload’s producer handed back, and on the error arm answers null, or an empty list where the field is a non-null list.
If your payload class already has an errors accessor, for example a getErrors() kept from Graphitron 9, Graphitron does not read it. The errors: field is filled from the exceptions your @error handlers claim, and is null when none were thrown, whatever the accessor holds. An errors list your service returns on success is therefore dropped; to report a business error as data, throw it and let a handler claim it.
Coming from Graphitron 9: one exception the handlers claim becomes one entry in errors:, with the response path described under path: below. Graphitron 9 could split one exception into several errors, each with its own path suffix; Graphitron 10 has no equivalent. A service that needs several errors reported for one request has no supported way to do it yet.
The Sakila example schema carries a worked end-to-end channel on Query.filmLookup: a union of @error types, one of them with a description: and one without, over a @service-returned payload. The classify-time fixtures live in graphitron/src/test/java/no/sikt/graphitron/rewrite/ErrorChannelClassificationTest.java (alongside the synthetic SakPayload record at no.sikt.graphitron.codereferences.dummyreferences.SakPayload). When you wire your first error channel, either is the right shape to copy.
Handler dispatch: source order, cause-chain unwrap
Dispatch calls ErrorRouter.claim, whose match loop is straightforward:
for (Mapping mapping : mappings) {
for (Throwable t = thrown; t != null; t = t.getCause()) {
if (mapping.match(thrown, t)) {
return t; // and, when t != thrown, records thrown as a chain root of t
}
}
}
return null;
A claimed exception goes into the payload’s errors list; null falls through to surfaceClientErrorOrRedact(thrown, env). (ErrorRouterClassGenerator.buildClaimMethod.)
Two facts to internalise:
-
Source order wins. Mappings are walked in the order the channel’s types appear in the SDL (and within a type, in
handlers:declaration order). The first mapping that returnstruefrommatch(thrown, t)is the answer. Order matters when one handler is more specific than another — declare the narrow one first. -
The cause chain is unwrapped per mapping. For each mapping, the loop walks the thrown exception, then
getCause(), then the cause’s cause, and so on. The result is "first (mapping, throwable-in-chain) pair that matches", not "first throwable matched against any mapping". ARuntimeExceptionwrapping aDataAccessExceptionwill match aDATABASEhandler attached to the inner exception even if the outer exception class isn’t itself in any handler. This is the intended shape: business exceptions surfaced through framework wrappers route to the typed channel. ADATABASEhandler’smatchesreaches further than the exception it claims: it reads the messages of every exception fromthrowndown to the matchedSQLException, so it sees the SQL text jOOQ’sDataAccessExceptioncarries. The matchedSQLExceptionis still what goes intoerrors, andcode/sqlStateare still read off it.
The classifier rejects duplicate handler criteria within one variant across the channel (Rule 8). Two handlers with identical (handler, className, code, sqlState, matches) are unreachable for the second declaration; the build fails rather than silently picking one. Cross-variant overlap is allowed: a GENERIC handler for IllegalArgumentException and a DATABASE handler for sqlState: "23514" can coexist on the same channel because their match predicates inspect orthogonal fields.
VALIDATION is special-cased. There is at most one VALIDATION handler per channel (Rule 7). It turns on Bean Validation for every @service field whose payload carries the channel: before the service method runs, Graphitron validates what each method parameter receives as a class you wrote (a Java record or a bean bound to an SDL input) or as a jOOQ record. A list parameter is validated element by element. Every violation becomes one entry in the errors list, typed as the VALIDATION member, with the constraint’s own interpolated message, and the service is not called. The validation never enters the dispatch loop.
public record FilmDraft(@NotBlank String title) {}
A class is validated whole, with the jakarta.validation constraints declared on it. Nested classes are validated only where you ask for it with @Valid, as Bean Validation always does.
A jOOQ record is validated column by column, for the columns the record writes: each column is checked against the constraints on the record’s property for it. Those are the ones jOOQ generates when <validationAnnotations> is on (@Size on a varchar(n) column, @NotNull on a NOT NULL one) and any you map onto the record yourself. A column the request left out is neither written nor checked, so a record that sets two columns does not fail on the others; a column the request sets to null is written as NULL and checked. That holds for a column the database declares NOT NULL too, whatever else the same input sends: a node id decoded into the record beside it does not drop the null. (The exception, for now, is a record whose input holds a list of node ids or a node id of several types: such a record is built the older way, and there a null on a NOT NULL column is dropped when another value is loaded into the record after it, so that column is neither written nor checked.) Key columns decoded from a node id are not checked, and neither is a constraint on the record class as a whole. Graphitron finds a column’s property through the getter jOOQ’s default generator strategy writes: get, then the column’s SQL name with each underscore-separated word capitalised and the rest of it lower-cased (BILDE gives getBilde, film_id gives getFilmId). If your generator strategy names getters differently, that column is not checked, and the build warns VALIDATION_COLUMN_UNCHECKED at each validating field whose record writes such columns, naming them. Silence it by adding VALIDATION_COLUMN_UNCHECKED to <lint><disabledRules>, or leave the field’s type out with <lint><excludedTypes>.
A violation’s path names the SDL input fields, not the Java members: the field’s path, the argument, the element index for a list, then the input fields down to the violated value (["countFilmDrafts", "in", "1", "title"]). Where an input field flattens onto the class or record from a grouping input, the path keeps the grouping field. A class-level constraint ends the path at the argument (or element).
Only the values a parameter receives as a class you wrote or a jOOQ record are validated. A scalar or enum argument, an input read field by field into scalar parameters, and an input passed through as a Map are passed through unchecked; to constrain one, take the argument as an input bound to a record, bean or jOOQ record. Constraints attached to Graphitron’s own generated <outputPackage>.inputs classes are not read: attach them to what the service takes. Validation runs after Graphitron has resolved the request’s tenant and decoded any node ids in the arguments, so a client error from either of those is reported instead of the violations. (A @mutation field’s character length check is separate and described below.)
Before a @mutation INSERT, UPDATE or UPSERT runs its statement, every string it writes to a column with a declared character length (varchar(n), char(n)) is checked against that length. A value that is too long is rejected with the message size must be between 0 and n, a path pointing at the input field (["createFilm", "in", "title"], or ["createFilms", "in", "1", "title"] for the second element of a list input), and extensions.constraint set to Size. Nothing is written: in a list input, one over-long value rejects the whole call. Values are counted in characters. On an Oracle column declared with byte length semantics a value can fit in characters and still exceed the column’s bytes, and the database rejects it as before.
Where the error goes depends on the payload:
-
No errors field, or the mutation returns its
@tabletype or an ID directly: the error is a top-level error with classificationValidationError, and the field isnull. -
An errors field with a
{handler: VALIDATION}member: the error is an entry in the errors list, typed as that member. -
An errors field without a
VALIDATIONmember: no check runs and the value reaches the database, because aDATABASEhandler there may already be catching the overflow. The build warns (dml-write-length-unrouted); add{handler: VALIDATION}to one@errortype to have the value checked.
Coming from Graphitron 9: the error type <recordValidation><schemaErrorType> named is the one to give {handler: VALIDATION}. Graphitron 10 has no <recordValidation> setting; the constraints jOOQ’s <validationAnnotations> generates are checked on the jOOQ records a @service method takes, so a too-long value still answers size must be between 0 and n.
Catching Graphitron’s own client errors
Generated code reports a client mistake by throwing GraphitronClientException. Examples are a tenant your connection source refuses, a node id that decodes to the wrong type, and an out-of-range page size or an invalid cursor (except that a cursor whose database-read text was edited fails when the page runs). Graphitron generates this class into your output package, at <outputPackage>.schema.GraphitronClientException. To deliver these errors as data in a payload, rather than as top-level errors, give an @error type a GENERIC handler that names it:
type InvalidInput @error(handlers: [{
handler: GENERIC,
className: "com.example.generated.schema.GraphitronClientException"
}]) {
path: [String!]!
message: String!
}
The build accepts the name before the class has ever been compiled, so a clean checkout works. Extra fields on the type read from graphql.GraphqlErrorException, the class it extends. Prefer this over a handler on graphql.GraphqlErrorException itself: that also catches every other GraphqlErrorException your services throw, and it requires graphql-java as a direct dependency of your module.
Only the name in this execution’s own output package is recognised this way. A project with two Graphitron executions that names the other execution’s client exception gets the ordinary classpath rule for it.
Coming from Graphitron 9: this is how to keep the in-payload shape Graphitron 9 gave these errors on mutations.
To change only the wording, and keep the error at the top level, override FetcherErrorResponse.clientErrorMessage instead; see Choosing what the client reads.
description: overrides message:, and nothing else
Set description: on a handler entry and the message: field of that entry’s @error type reads the authored string instead of the matched exception’s getMessage(). Leave it off and message: reads the source’s own message. Nothing else about the error changes.
That last sentence is the load-bearing one. Dispatch is source-direct: the matched Throwable itself is what goes into the payload’s errors list (the outcome’s ErrorList(List.of(t))), and the override is resolved on the read side, at the message: fetcher. So the matched exception is never wrapped or substituted, which is what keeps three other things pointed at the live object:
-
A
unioncarrier resolves__typenameby running the members' own dispatch mappings against the source, and against the exceptions that wrapped it when it was claimed, so the override cannot move an error to a different type. The resolver tries every member’s mappings before anyVALIDATIONmember’sGraphQLErrortest, so an exception that is also aGraphQLErrorresolves to the type dispatch chose. -
Extra fields on the error type still read their accessors off the live exception. An
attempted: Int @field(name: "attemptedId")slot readsgetAttemptedId()from the throwable that was actually caught, alongside an authoredmessage:. -
The build-time check that every extra field resolves to a real accessor on each handler’s declared source class stays a build-time guarantee, rather than becoming a runtime property-fetcher miss.
The override is per handler, not per channel or per type. Two @error types on one channel, one with description: and one without, produce an authored message for the first and getMessage() for the second; two handler entries on one type behave the same way.
Since it is per handler, only entries that can match carry one. A {handler: VALIDATION} entry cannot: the build rejects description: there, because the validator emits one GraphQLError per constraint violation, each already carrying that violation’s own interpolated message, and collapsing them all to one authored string would discard exactly the per-violation detail Bean Validation exists to produce. Put the client-facing string on the constraint annotation’s own message attribute instead.
path:, message: field fetchers
Every @error type’s path: [String!]! and message: String! slots get synthesised data fetchers. The slots are matched by name; an @error type without one of them is rejected at classify time.
path: answers the response path of the field whose payload holds the error (ErrorTypeFetcherClassGenerator.pathMethod; the schema class only wires the <ErrorType>Fetchers::path reference). It uses the field’s alias when the query gives one, and carries a list index when the payload hangs off an element of a list: a child @service payload under the second of a list of films answers ["films", "1", "<childField>"].
A GraphQLError that carries its own path keeps it. Two producers build one: Bean Validation (ConstraintViolations.toGraphQLError records each violation’s input path) and the column-length check before a @mutation write (see above), so their per-element input paths survive intact. A GraphQLError with no path, such as graphitron’s own GraphitronClientException claimed by a handler, answers the holder like any other exception.
The path is the GraphQL response path, not the mutation argument path. For:
mutation { createFilm(input: {...}) { film { title } errors { path message } } }
an exception thrown by createFilm and matched into errors[0] produces path: ["createFilm"]. To convey which input field triggered the error, encode that into the exception itself (the constraint or the validation-handler payload) and surface it through message: or a custom field on the error type.
message: resolves in two steps, in this order:
-
If the source is a
Throwable, the fetcher walks its own@errortype’s handler list in declaration order. The first handler that matches the source and carries adescription:gives the default message; with none, the default isThrowable.getMessage(). A configuredFetcherErrorResponsecan then replace the default throughmatchedMessage; without one,message:reads the default. -
Otherwise, if the source is a
GraphQLError,message:readsGraphQLError.getMessage(). This is the VALIDATION path:ConstraintViolations.toGraphQLErrorbuildsGraphQLErrorinstances that need not be `Throwable`s at all.
The Throwable step runs first on purpose, whatever the handlers declare, because a source can be both shapes at once: graphql.GraphQLError is a plain interface, so an author’s own exception class may implement it (Graphitron’s own generated GraphitronClientException does, by extending GraphqlErrorException). For such a class the two steps would return different strings, and resolving the GraphQLError step first would silently drop an authored description:, and keep the exception from matchedMessage.
The walk is per @error type rather than channel-wide. The union’s type resolver runs the same mappings, through the same re-check against the exceptions that wrapped the source when dispatch claimed it, so message: agrees with the __typename the client reads in the same selection set.
If you want a localised or sanitised message and description: is too static for it (a per-request locale, say), compute it in FetcherErrorResponse.matchedMessage; see Choosing what the client reads. That also reaches an exception class you do not own, such as jOOQ’s DataAccessException, and can quote the error’s reference.
Unmatched exceptions: redact and correlate
When no handler matches, the router first walks the exception’s cause chain for a GraphitronClientException, the error graphitron itself raises for a client mistake: a tenant your connection source refuses, a malformed or wrong-type node id, an out-of-range page size or an invalid cursor (except that a cursor whose database-read text was edited fails when the page runs). If it finds one, that error reaches the response’s top-level errors with its own message, or the one your FetcherErrorResponse.clientErrorMessage returns, and with the failing field’s path and locations, and the field resolves to null; on a non-null field it is the only error at that path, as with a redacted error, and the null bubbles to the nearest nullable parent. All of this is exactly as on a field without an error channel, and nothing is logged (unless your clientErrorMessage throws or returns null, which logs one ERROR line naming the field’s path). A handler you declare still wins, because handlers are tried first. Every other unmatched exception runs the redact path (ErrorRouterClassGenerator.redactBody):
String reference = reportUnmatched(thrown, env, "Unmatched exception in fetcher");
String message = answer(configured(env, FetcherErrorResponse.class),
response -> response.unmatchedMessage(thrown, reference, env), () -> "reference = " + reference);
return DataFetcherResult.<P>newResult()
.data(null)
.error(GraphqlErrorBuilder.newError(env)
.message(message)
.build())
.build();
reportUnmatched mints the reference and logs the exception, once per request however many fields the exception failed: a batched child query that fails under 400 parents produces 400 field errors, one log record, and one reference that all 400 errors quote. Two batches that fail separately are two records with two references. (A @service of yours that rethrows one cached exception wrapped in a CompletionException for two batches reads as one failure.)
The reference and unmatchedMessage are a FetcherErrorResponse's when you configure one, and its defaults otherwise: a random UUID, and "An error occurred. Reference: <reference>.". Two consequences:
-
Untyped exceptions don’t leak details to clients. The user-facing message is "An error occurred. Reference: <UUID>."; the original message stays in the server log. This is the fallback behaviour, intentional: only exceptions you’ve explicitly opted into via
@errorflow as data. -
The correlation ID joins the log line and the client response. Operations can grep the logs for the UUID a customer reports back, see the original stack, and decide whether to add a handler. This is the shape any new error category goes through before earning a typed channel slot.
Add a typed channel slot when an untyped fallthrough turns out to be a regular, expected condition (not a bug). Leave it as a fallthrough when it really is a bug: the redacted shape is exactly what you want for a 500-class condition.
Choosing how unmatched exceptions are logged
By default the redact path logs through the ErrorRouter logger, and what it logs depends on where the exception came from.
When the exception comes from the database driver (a java.sql.SQLException is on its cause chain), the ERROR record is one line: the path of the field that failed, the exception class, the driver exception’s class, its SQL state and vendor code, and the first line of the driver’s message, shortened to 240 characters:
Unmatched exception in fetcher; correlation id = 1c0e...; path = /films[0]/actors; org.jooq.exception.DataAccessException: org.postgresql.util.PSQLException [57014/0] ERROR: canceling statement due to statement timeout
The SQL statement is not in it; for a batched query that statement grows with the batch. Nor are the driver’s detail lines, where PostgreSQL and Oracle name the values involved. A driver can still put a value in its first line, so configure a FetcherErrorLog if nothing from the database may reach your log. The full exception, statement included, is logged at DEBUG under the same reference.
Any other exception is logged at ERROR with its stack trace, message and cause chain included. An exception message can carry row data.
To decide yourself what reaches your logs, give the runtime a FetcherErrorLog:
var runtime = Graphitron.runtime(SQLDialect.ORACLE)
.withFetcherErrorLog((thrown, reference, env) ->
LOG.error("Unmatched exception at {}; reference = {}; {}",
env.getExecutionStepInfo().getPath(), reference, Sanitiser.describe(thrown)));
var engine = runtime.newGraphQL(Graphitron.buildSchema(b -> {})).build();
FetcherErrorLog is generated into your schema package next to GraphitronRuntime. Graphitron calls it in place of its own log line, once per unmatched exception per request in the same way, with the full exception as the first failing field caught it, the reference the client receives, and that field’s DataFetchingEnvironment (its path, field definition and arguments). To write the same one-line summary yourself, call ErrorRouter.describe(thrown, env), which is empty for an exception that did not come from the driver. The client’s response does not change: it is still "An error occurred. Reference: <reference>." Graphitron then logs nothing about the exception, so the reference is the only thing that joins a client’s report to your log line; log it.
Levels, sanitising and rate limiting are yours to build inside the callback. A common shape logs the exception class chain plus SQLException.getSQLState() and getErrorCode() and never getMessage(), picks WARN for exceptions that mean the client sent bad data, and rate-limits stack traces for connection failures so an outage does not flood the log.
If your log throws, the client still gets the redacted error, and Graphitron logs one ERROR line naming your log’s class, the class of what it threw and the reference, without either exception’s message or stack trace. Only JVM-fatal errors (VirtualMachineError, such as OutOfMemoryError) propagate.
The escape-hatch engine (Graphitron.newGraphQL()) has no runtime, so withFetcherErrorLog cannot reach it. There, put the log into each request’s context under its class: Graphitron.newExecutionInput(dsl, …).graphQLContext(b → b.put(FetcherErrorLog.class, log)). A request built without that entry gets the default line; nothing warns you, so build every request through one helper of your own.
In a <tenantColumn> build, a field fanned out across tenants that fails or times out for one tenant reaches tenantFailed(tenantKey, cause, reference, env), where a timeout arrives as a java.util.concurrent.TimeoutException. Its default calls unmatched(cause, reference, env); override it to log the tenant too. Each failed tenant is its own failure with its own reference, so this is the one place unmatched is called more than once for a field. Without a FetcherErrorLog, a tenant’s database failure is logged as the same one-line summary at ERROR, with the exception at DEBUG.
Logging the errors a handler caught
A handler that catches an exception puts it in the payload and logs nothing, which is right for a business error the client is meant to handle. For a broad handler last in a union (a catch-all) it means a database outage on a mutation reaches the client and never the log. This is the catch-all a consumer keeping Graphitron 9’s payload errors declares: the member that catches Graphitron’s own client errors, with two broad handlers appended last so they only see what every earlier handler passed over.
type UgyldigInput @error(handlers: [
{handler: GENERIC, className: "com.example.generated.schema.GraphitronClientException"},
{handler: GENERIC, className: "java.lang.IllegalArgumentException"},
{handler: GENERIC, className: "org.jooq.exception.DataAccessException",
description: "Operasjonen kunne ikke utføres."}
]) {
path: [String!]!
message: String!
}
To log what it catches, override matched on your FetcherErrorLog:
final class FsErrorLog implements FetcherErrorLog {
public void unmatched(Throwable thrown, String reference, DataFetchingEnvironment env) {
LOG.error("Unhandled error; reference = {}", reference, thrown);
}
@Override
public void matched(Throwable thrown, Throwable claimed, String reference, DataFetchingEnvironment env) {
if (claimed instanceof DataAccessException) {
LOG.error("Database error returned in payload; reference = {}", reference, thrown);
}
}
}
Graphitron calls matched once for each exception a handler catches in a request, however many fields it failed, with the exception the fetcher threw, the one the handler caught (the same object, or a link of its cause chain), the reference the client can be given for it, and the failing field’s environment. Its default does nothing, so a log that does not override it, a lambda among them, behaves as before. VALIDATION errors and the column-length check are not exceptions and do not reach it.
Choosing what the client reads
description: gives a handler a fixed message. When the message has to be computed from the exception, or has to carry the reference, give the runtime a FetcherErrorResponse, generated into your schema package next to FetcherErrorLog:
var runtime = Graphitron.runtime(SQLDialect.ORACLE)
.withFetcherErrorLog(new FsErrorLog())
.withFetcherErrorResponse(new FsErrorResponse());
All four of its methods have defaults that reproduce what Graphitron does without one, so override only what you need:
final class FsErrorResponse implements FetcherErrorResponse {
@Override
public String reference(Throwable thrown, DataFetchingEnvironment env) {
String traceId = env.getGraphQlContext().get(TRACE_ID);
return traceId != null ? traceId : FetcherErrorResponse.super.reference(thrown, env);
}
@Override
public String matchedMessage(Throwable source, String defaultMessage, String reference,
DataFetchingEnvironment env) {
if (!"UgyldigInput".equals(((GraphQLNamedType) env.getParentType()).getName())) {
return defaultMessage;
}
return FsMessages.describe(source, defaultMessage) + " Referanse: " + reference;
}
@Override
public String clientErrorMessage(GraphitronClientException error, DataFetchingEnvironment env) {
return FsMessages.tenantRefusal(error.getMessage())
.orElseGet(() -> FetcherErrorResponse.super.clientErrorMessage(error, env));
}
@Override
public String unmatchedMessage(Throwable thrown, String reference, DataFetchingEnvironment env) {
return "An exception occurred. The error has been logged with id " + reference
+ FsMessages.hint(thrown).map(h -> ": " + h).orElse(".");
}
}
-
referencemints the text that joins a client’s report to your log line. The default is a random UUID. Return a trace id to let an operator go straight from a support ticket to the trace. Read it from somewhere the fetcher’s thread can see: a fetcher may run on a thread that does not carry your request’s tracing context, so put the trace id into the request’sGraphQLContextwhen you build the execution input, and read it here. Graphitron hands the same reference to yourFetcherErrorLogand tomatchedMessageandunmatchedMessage, so they always agree. A runtime with a log and no response uses the default reference. -
matchedMessageis called when a payload error’smessage:is read, with the exception the handler caught, the message Graphitron would return (the handler’sdescription:, else the exception’s own message), the reference and themessagefield’s environment.env.getParentType()is the@errortype, which is how to change the message of one type only. ReturndefaultMessagefor errors you leave alone. -
clientErrorMessageis the top-level error’s message for aGraphitronClientExceptionno handler caught, for example a tenant your connection source refuses. It receives the exception and the failing field’s environment. The default is the exception’s own message. There is no reference: Graphitron neither logs these errors nor gives them one. All of Graphitron’s client errors are one class, so tell them apart by message; that text is Graphitron’s and may be reworded in a release, so match it loosely and fall back toFetcherErrorResponse.super.clientErrorMessage(error, env)when nothing matches. -
unmatchedMessageis the top-level error’s message when no handler caught the exception. The default is "An error occurred. Reference: <reference>.". It is the client-facing text of a fault you did not plan for, so do not put the exception’s message in it unless you know what it contains. Branch on the exception’s class instead where Graphitron gives you one worth reading: a list-inputUPDATEwhose keys match no row throwsZeroRowsMatchedException, whose accessors count the missed rows; see When an UPDATE key matches no row.
If a method throws or returns null, the client gets the default text, and Graphitron logs one ERROR line naming your class, the class of what it threw and the reference (the field’s path, for clientErrorMessage). As with FetcherErrorLog, the escape-hatch engine has no runtime: put the response into each request’s context under its class, graphQLContext(b → b.put(FetcherErrorResponse.class, response)).
With graphitron-jakarta-rest, a fault thrown while building the execution input (the database down when newExecutionInput opens a connection) never reaches a fetcher, and GraphqlHttpHandler answers it itself. Override GraphitronApplication.newReference(Throwable) and redactedMessage(Throwable, String) to give it the same reference and text as your FetcherErrorResponse; the library cannot see the generated interface, so have both call the same helper of yours.
Pitfall: a catch-all can leak. A handler on DataAccessException without description: and without a matchedMessage that replaces it returns jOOQ’s message to the client, and that message holds the SQL statement and, on Oracle, row values. Give a catch-all a description: as its safe default. A catch-all on RuntimeException also catches GraphitronClientException, since handlers are tried before Graphitron surfaces its own client errors; declare a handler for that class first if the two should read differently.
Pitfalls
-
Source order is significant. Declare narrow handlers (with
matches:substrings, more specificclassName:subclasses) before broad ones. The first match wins, not the most specific. -
description:changesmessage:and nothing else. It does not move an error between union members, and it does not affect the extra fields, which keep reading the live exception. If you need the whole error shaped differently, that is a different@errortype, not a description. -
path:is the response path. If you need to point at an input argument, encode it in the exception or in a custom field on the error type. -
VALIDATIONruns pre-execution, on the classes and jOOQ records you bind. The Bean-Validation handler intercepts before the service method runs, checking the constraints on the records, beans and jOOQ records its parameters receive (a scalar argument is not checked; see Bean Validation), and the column-length check before a payload-returning@mutationwrites; their results bypass the dispatch loop and route straight into the errors field. There’s at most oneVALIDATIONhandler per channel. -
Cause-chain unwrap is per mapping, not per source-order step. If a wrapping exception declares a handler at the channel and the wrapped exception declares a different one, the wrapping exception wins for any mapping it matches first — even if the wrapped exception would match a later mapping more specifically. Keep handler tuples disjoint across the wrap boundary.
-
A catch-all can leak. A broad handler without
description:returns the exception’s own message, jOOQ’s SQL text included, unless amatchedMessagereplaces it; see Choosing what the client reads. -
Unmatched flows redact, except graphitron’s own client errors. A
GraphitronClientExceptionno handler claims surfaces as a top-level error with its own message (or yourclientErrorMessage’s), as described under unmatched exceptions. If a developer expects a specific exception class to surface to the client and it doesn’t, the most likely cause is "no `@errortype covers it"; check the redaction log (or yourFetcherErrorLog) for a correlation ID, then add the handler. -
An errors accessor on the payload class is ignored. A
getErrors()orerrors()on the class your service returns is never read:errors:holds what the handlers claimed and isnullotherwise, so an errors list the service fills on success is dropped. -
On the escape-hatch path, an error payload from a
@servicefield says the call failed, not that nothing was written. On the owned-connection path it does say nothing was written: a claimed exception still fails the field, and the field’s one transaction rolls back (Transactions on the owned-connection path). A transaction your service opens inside the field joins it, so catching that transaction’s failure inside the service does not save the field: it is reported as failed, with an error that says a nested transaction failed, beside any payload. Elsewhere graphitron opens no transaction around a@serviceinvocation (see the@serviceconstraint), so a method that threw partway through a batch may already have committed the rows it got to, and the payload is well-formed either way. A payload-returning DML@mutationcarrier does carry the rollback promise: its per-row writes run inside one transaction graphitron opens, so an error payload from one means nothing was written. A payload-returning@routineMutation write carries it for statement 1 only, the caveat that page already publishes. A service that needs the promise must open the transaction itself; the trap is a service whose own javadoc claims all-or-nothing, since believing the contract is satisfied somewhere is what makes a partial commit invisible rather than merely surprising. -
No payload, no channel.
@erroronly takes effect when the type appears as (or in a union behind) anerrors:field on a payload one of the three producer families returns: a@servicefield, at a root or below one, a payload-returning DML@mutation, or a payload-returning@routineMutation write. A standalone@errortype with no carrier is rejected at classify time.
See also
-
@erroris the directive surface and the handler-tuple specification. -
Three producer families sit upstream of an errors channel:
@servicepayloads, payload-returning DML@mutationcarriers, and payload-returning@routineMutation writes. -
How-to: Result-type variants covers the payload’s backing-class shape (reflected from its
@serviceproducer’s return type).