Handling Errors
Mach provides two ways to turn application errors into appropriate HTTP responses.
When an error is detected directly inside a controller action or minimal API handler, return an HTTP result. When an error occurs deeper in the application, such as inside a service or helper function, you can throw an HTTP exception and let Mach’s built-in exception middleware convert it into a response.
Returning Errors from Handlers
Section titled “Returning Errors from Handlers”When an error is detected directly inside a controller action or minimal API handler, return the appropriate result:
app.mapGet("/users/{id}", [](mach::Context& context) { const auto id = context.routeParam<int>("id");
if (!userExists(id)) { return mach::notFound("User not found."); }
// ...});There is usually no reason to throw an exception here because the handler can return the HTTP response directly.
Throwing HTTP Exceptions
Section titled “Throwing HTTP Exceptions”Inside services or helper functions, returning an HTTP result may not fit the function’s responsibility.
In these cases, throw one of Mach’s HTTP exceptions:
User UserService::getUser(int id) { auto user = m_repository.findById(id);
if (!user) { throw mach::NotFoundException("User not found."); }
return *user;}The exception does not need to be caught by the endpoint handler:
app.mapGet("/users/{id}", [&](mach::Context& context) { const auto id = context.routeParam<int>("id");
return mach::ok(userService.getUser(id));});If getUser() throws mach::NotFoundException, Mach’s built-in exception middleware converts it into a 404 Not Found response using the exception message.
Available HTTP Exceptions
Section titled “Available HTTP Exceptions”Mach provides HttpException as the base HTTP exception type, along with specialized exceptions for common HTTP errors:
| Exception | HTTP Response |
|---|---|
BadRequestException |
400 Bad Request |
UnauthorizedException |
401 Unauthorized |
ForbiddenException |
403 Forbidden |
NotFoundException |
404 Not Found |
ConflictException |
409 Conflict |
Use the specialized exception that best represents the failure.
When to Return and When to Throw
Section titled “When to Return and When to Throw”Return an HTTP result when the code is already responsible for producing an HTTP response:
return mach::notFound("User not found.");Throw an HTTP exception when the failure occurs in code that should not need to construct an HTTP response:
throw mach::NotFoundException("User not found.");This keeps HTTP response logic in handlers while allowing services and helper functions to report HTTP failures without returning response types.
Next Steps
Section titled “Next Steps”For details about Mach’s HTTP exception types, see HttpException.