Web Application Errors
You can give errors a consistent HTTP response format, even when they come
from reusable components or external libraries. In ntex, an error domain
chooses how errors become responses. Your handlers can return ordinary
Result values instead of building error responses by hand.
Each application state selects its domain with the State::Error associated
type. Every error that can reach the application must implement
WebResponseError for that domain. A missing implementation prevents the
application from compiling.
The domain type names a set of rendering rules. It does not have to be an error that handlers return. You can use your application’s error enum, as in the example below, or a separate empty marker type.
DefaultError provides plain-text responses for common ntex errors. Define a
custom domain if your API needs JSON bodies, extra headers, error codes, or
other metadata. You then choose how each error is rendered.
Where an error occurs determines when ntex converts it. Extractor and handler errors become responses inside the route. Errors from filters, middleware, and lower-level services remain service errors until they leave the application stack.
Default Error Handling
Use DefaultError for plain-text responses to common ntex errors. Every
application state chooses its error domain through the State trait:
use ntex::web;
#[derive(Clone)]
struct AppState;
impl web::State for AppState {
type Error = web::DefaultError;
}
Here, the application selects DefaultError. Its responses contain the
error’s Display text with the text/plain content type:
- Malformed request data returns
400 Bad Request. This includes invalid query strings, JSON or form bodies, and a wrongContent-Type. - JSON and form bodies over their configured limit return
413 Payload Too Large. - A malformed form
Content-Lengthreturns411 Length Required. - Path segments that fail to deserialize return
404 Not Found. - Response serialization failures return
500 Internal Server Error. For example, aJson<T>responder might fail to encode its value.
The Bytes and String extractors use their own PayloadError. Overflow
returns 413 Payload Too Large; other payload errors return 400 Bad Request,
including invalid text or a content-type check that fails.
Applications with () or AppState<T> state select DefaultError
automatically. They usually need no further error configuration.
DefaultError selects these implementations as a marker; ntex does not
construct it at runtime. It does not make every Rust error renderable. A
custom error still needs a WebResponseError<St, DefaultError> implementation
or an InternalError wrapper.
Returning Errors from Handlers
Return Result from a handler, as you would from another async Rust
function. ntex uses the successful value as the response or turns the error
into an error response.
The successful value must implement Responder. The error must implement
WebResponseError for the application’s domain. The Result responder
renders the error inside the route as soon as the handler returns.
For simple cases, use the helpers in web::error to choose an HTTP status
without defining a new error type:
use ntex::web::{self, App, InternalError};
async fn create_user(
) -> Result<&'static str, InternalError<&'static str>> {
Err(web::error::ErrorBadRequest("Invalid user"))
}
fn main() {
App::default().route(
"/users",
web::post().to(create_user),
);
}
The module has 39 Error* helpers, one for each common 4xx and 5xx status.
Examples include:
ErrorBadRequestErrorUnauthorizedErrorForbiddenErrorNotFoundErrorConflictErrorInternalServerError
Each helper returns an InternalError<T> with the chosen status and T’s
Display text as the body. These helpers are useful at an application
boundary, where you choose what the client should see.
The response body is public. Do not wrap database errors, tokens, internal paths, or other sensitive details directly. Log the original error and return a message that is safe for the client.
Use InternalError::from_response() when you need to supply a fully prepared
response instead of a status and plain-text body:
use ntex::web::{self, HttpResponse, InternalError};
async fn create_user(
) -> Result<&'static str, InternalError<&'static str>> {
Err(InternalError::from_response(
"duplicate user",
HttpResponse::Conflict()
.header("x-error-code", "user-exists")
.body("A user with that name already exists"),
))
}
Some error types implement WebResponseError for every domain. They work with
DefaultError and custom domains alike:
InternalError<T>, including everyError*helper.WebError<St, Err>, which holds a renderable error for that same state and domain. It erases the concrete type; it does not render the response yet.ntex::util::Either<A, B>, when bothAandBimplement the trait.std::convert::Infallible.
Custom Error Domains
Define a custom domain to control how your application renders errors,
including those from external components. Set State::Error to an
application-specific type. Then implement WebResponseError for each error
the application can produce.
The error_response() method receives application state, so it can use shared
configuration to build the response. By default, it returns
500 Internal Server Error with the error’s Display text as a plain-text
body. Override it to choose the status, headers, and body for each error.
For a JSON API, you can use a response builder’s json() method to serialize
a small error-body struct.
WebResponseError requires std::error::Error + 'static. Every error type
must therefore implement the standard Error trait. The example below derives
it with thiserror; add that crate to your Cargo.toml.
The example below keeps three application errors in one enum. It sends a
short, stable code for clients and a readable message for people. Duplicate
names return 409 Conflict; empty names and invalid JSON return 400 Bad Request. An unavailable dependency returns a generic 503 without exposing
its internal error:
use ntex::http::StatusCode;
use ntex::web::{
self, App, HttpResponse, WebResponseError, error::JsonPayloadError,
};
#[derive(Clone)]
struct AppState;
#[derive(Debug, thiserror::Error)]
enum ApiError {
#[error("User already exists")]
UserExists,
#[error("Name must not be empty")]
InvalidName,
#[error("Service temporarily unavailable")]
Unavailable,
}
impl web::State for AppState {
type Error = ApiError;
}
#[derive(serde::Serialize)]
struct ErrorBody {
code: &'static str,
message: &'static str,
}
fn error_json(
status: StatusCode,
code: &'static str,
message: &'static str,
) -> HttpResponse {
HttpResponse::builder(status).json(&ErrorBody { code, message })
}
impl WebResponseError<AppState, ApiError> for ApiError {
fn error_response(&self, _state: &AppState) -> HttpResponse {
let (status, code, message) = match self {
Self::UserExists => {
(StatusCode::CONFLICT, "user_exists", "User already exists")
}
Self::InvalidName => (
StatusCode::BAD_REQUEST,
"invalid_name",
"Name must not be empty",
),
Self::Unavailable => (
StatusCode::SERVICE_UNAVAILABLE,
"unavailable",
"Try again later",
),
};
error_json(status, code, message)
}
}
impl WebResponseError<AppState, ApiError> for JsonPayloadError {
fn error_response(&self, _state: &AppState) -> HttpResponse {
match self {
JsonPayloadError::Overflow => error_json(
StatusCode::PAYLOAD_TOO_LARGE,
"body_too_large",
"Request body is too large",
),
JsonPayloadError::ContentType => error_json(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"expected_json",
"Expected a JSON request",
),
_ => error_json(
StatusCode::BAD_REQUEST,
"invalid_json",
"Invalid JSON",
),
}
}
}
#[derive(serde::Deserialize)]
struct User {
name: String,
}
fn validate_name(name: &str) -> Result<&str, ApiError> {
let name = name.trim();
if name.is_empty() {
Err(ApiError::InvalidName)
} else if name == "admin" {
Err(ApiError::UserExists)
} else {
Ok(name)
}
}
async fn create_user(user: web::types::Json<User>) -> Result<String, ApiError> {
let name = validate_name(&user.name)?;
Ok(format!("Created {name}"))
}
fn main() {
let app =
App::<AppState>::new().route("/users", web::post().to(create_user));
}
The name check stands in for application logic; a real registration handler
would check uniqueness in its storage layer. Calling validate_name() with
? returns early on failure. ntex then renders the returned ApiError as,
for example, {"code":"user_exists","message":"User already exists"}. The
handler does not need to know how that error becomes JSON.
This example has two possible error types:
- The handler can return
ApiError. - The
Json<User>extractor can returnJsonPayloadErrorbefore ntex calls the handler.
Although ntex defines JsonPayloadError, your application can implement
WebResponseError<AppState, ApiError> for it. Rust’s orphan rules allow this
because AppState and ApiError are local types.
Selecting a custom domain replaces the application’s DefaultError
implementations. Add a mapping for every extractor, responder, filter,
middleware, or service error the application uses. Requiring these mappings
prevents an API from silently falling back to a response format or status it
did not choose.
Include errors that occur while ntex builds the response. A Json<T>
responder requires a mapping for web::error::JsonError. A Form<T> responder
requires one for serde_urlencoded::ser::Error.
Using ? and Converting Library Errors
? follows ordinary Rust conversion rules. It propagates the same error type,
or uses a From implementation to convert into the function’s declared error
type. Implementing WebResponseError only teaches ntex how to render an error;
it does not add a Rust conversion between errors.
When a library error needs an application-specific meaning, use map_err() at
the boundary. For example, invalid policy data loaded from your own storage
is a server problem, not a bad client request. Alongside the types above, you
could write:
#[derive(serde::Deserialize)]
struct AccountPolicy {
minimum_name_length: usize,
}
fn decode_policy(bytes: &[u8]) -> Result<AccountPolicy, ApiError> {
serde_json::from_slice(bytes).map_err(|err| {
log::error!("Cannot decode stored account policy: {err}");
ApiError::Unavailable
})
}
A handler returning Result<_, ApiError> can call decode_policy(bytes)?.
The original parsing error stays in the server log; the client sees only the
unavailable response. If callers need the original error for diagnostics,
store it as a source in your application error instead of discarding it.
thiserror can generate From implementations with #[from] when a direct
conversion is appropriate. Keep HTTP rendering separate from that decision.
Customizing Extractor Rejections
An invalid body fails before your handler runs. A handler’s return type does
not change that: Result<String, ApiError> does not turn a
JsonPayloadError into an ApiError. In the worked example, the separate
WebResponseError<AppState, ApiError> implementation for JsonPayloadError
provides the JSON rejection body.
That implementation deliberately differs from the default domain: a missing
or unsupported JSON content type returns 415 Unsupported Media Type, not
400. Overflow still returns 413, and malformed JSON returns 400. These
are your API’s choices, not changes to the extractor’s parsing rules.
JsonConfig configures the size limit and accepted content types; it has no
error_handler() callback. FormConfig and PayloadConfig do not provide
such a callback either. Use the error domain for application-wide formatting.
Map PathError, QueryPayloadError, UrlencodedError, or PayloadError in
the same way when you add those extractors to a custom-domain application.
For one route that needs to inspect a rejection itself, take
Result<Json<User>, JsonPayloadError> as its argument and match the result
inside the handler. This lets that handler choose its own response while
other routes keep the domain’s behavior. It also makes the handler responsible
for rejecting malformed or oversized input. Option<Json<User>> instead
hides the reason for failure, so it is a poor choice when you need distinct
error codes. See Optional Extractors
for the body-consumption caveats.
Logging Errors Without Exposing Them
Treat the response body and the diagnostic log as two different audiences.
An access log can record the 500 status, but it does not tell you which
query or dependency failed. Log useful context where you still have it, such
as the operation name and a nonsecret request identifier, before mapping a
library error to a safe application error.
Do not rely on every handler error being logged automatically. The Result
responder calls error_response(); that conversion does not itself log the
error. ntex emits some extractor diagnostics at debug level, but that is not
an application logging policy. Initialize a logger or tracing integration in
your executable, and choose where each unexpected failure is recorded so you
do not log it repeatedly at every layer. Expected validation failures usually
need less attention than an unavailable database.
Where Error Responses Travel
Where an error occurs determines what middleware sees. Errors converted inside a route reach middleware as responses. Service-layer errors remain errors until the outer application service renders them.
ntex converts extractor errors, handler Result errors, and responder
serialization errors while the route runs. These ordinary responses pass
through resource, scope, and application middleware. Response middleware can
inspect or modify them.
Filters, middleware services, and custom web services return errors through
the service layer. ntex erases their concrete types into WebError as they
travel out through the stack. The outer application service then calls
error_response().
Middleware using ctx.call(...).await? therefore sees an error before a
rendered response exists. To inspect that response or add headers, catch the
error and convert it in the middleware.
In normal handlers, return Result<T, E> and let the responder convert it.
You usually need WebError only when implementing a lower-level web service,
filter, or middleware whose error type is already type-erased.
The WebError::from_err Escape Hatch
WebError::from_err(error) stores an error that already implements
WebResponseError for the target state and domain. It preserves that
implementation for later rendering; it is not a way to make an arbitrary Rust
error renderable.
There is no blanket From<E> conversion into WebError, so ? alone cannot
perform this wrapping. Convert explicitly with map_err(WebError::from_err).
This standalone handler shows both decisions: first choose a safe 400
response, then erase the concrete error type:
use ntex::web::{self, WebError, types::Path};
async fn revision(value: Path<String>) -> Result<String, WebError> {
let number = value
.parse::<u32>()
.map_err(|_| {
web::error::ErrorBadRequest(
"Revision must be a nonnegative integer",
)
})
.map_err(WebError::from_err)?;
Ok(format!("Revision {number}"))
}
For this small handler, returning InternalError<&'static str> directly
would be simpler. The explicit wrapping becomes useful when a service
boundary requires WebError. Inside that boundary, ? still works normally
on calls that already return the matching WebError<St, St::Error>.
Test the Rendered Response
Test the HTTP response your client receives, including its status, headers, and body. Checking only the Rust error value does not test the HTTP contract. This example checks both the status and the public message of a conflict response:
use ntex::http::StatusCode;
use ntex::web::{self, App};
#[derive(Clone)]
struct AppState;
impl web::State for AppState {
type Error = web::DefaultError;
}
async fn create_user() -> Result<&'static str, web::InternalError<&'static str>>
{
Err(web::error::ErrorConflict("User already exists"))
}
#[ntex::test]
async fn duplicate_user_response() {
let app = web::test::init_service_st(
AppState,
App::<AppState>::new().route("/users", web::post().to(create_user)),
)
.await;
let request = web::test::TestRequest::post().uri("/users").to_request();
let response = web::test::call_service(&app, request).await;
assert_eq!(response.status(), StatusCode::CONFLICT);
assert_eq!(web::test::read_body(response).await, "User already exists");
}
For the JSON API above, also deserialize the response body and assert its
code and message fields. Cover failures before the handler as well as
inside it: malformed JSON, a wrong content type, and an over-limit body should
all keep the API’s error format. Testing covers the test
helpers and how to organize these checks.