I’m working on an Axum-based application in Rust, where one of my handlers receives a JSON payload that is deserialized into a MyRequest
struct. The struct contains a field my_enum
of type MyEnum
, which is an enum with variants Foo
and Bar
.
Here’s a simplified version of my code:
use axum::{extract::Json, response::IntoResponse};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum MyEnum {
Foo,
Bar,
}
#[derive(Deserialize)]
struct MyRequest {
my_enum: MyEnum,
// other fields...
}
async fn my_handler(
payload: Result<Json<MyRequest>, axum::extract::rejection::JsonRejection>,
) -> impl IntoResponse {
match payload {
Ok(Json(request)) => {
// Handle the request...
}
Err(e) => {
// Handle the error...
// Right now, I'm just checking the error message.
if e.to_string().contains("my_enum") {
// Specific handling for enum deserialization error
} else {
// Generic error handling
}
}
}
}
The Problem
Currently, if the incoming JSON contains an invalid value for my_enum
, Serde fails to deserialize it, and Axum returns a JsonRejection
. To differentiate between errors caused by an invalid my_enum
value and other potential errors, I’m inspecting the error message with a string check like e.to_string().contains("my_enum")
.
This approach feels brittle because it relies on the specific wording of the error message, which could change and isn’t guaranteed to be consistent.
My Question
Is there a way to configure Serde to throw a specific error (or to more reliably identify the deserialization failure) when the value assigned to the my_enum
field in MyRequest
cannot be deserialized? Ideally, I’d like to handle this scenario without resorting to fragile string matching.
What I’ve Tried
I’m currently using Axum’s standard pattern for handling deserialization:
payload: Result<Json<MyRequest>, axum::extract::rejection::JsonRejection>
And then inspecting the error like this:
if e.to_string().contains("my_enum") {
// Specific handling for enum deserialization error
}
However, as mentioned, this approach isn’t ideal due to its dependency on error message content.
What I’m Looking For
I’m seeking a more robust solution that allows me to reliably detect when the deserialization of my_enum
fails, preferably by leveraging Serde’s capabilities or customizing the deserialization process.