Exception
Mayari provides a built-in exception utility for throwing structured HTTP errors anywhere in your app, whether inside a route handler, a Guard rule, a Validator, or an Interceptor.
When an exception is thrown, Mayari's global error pipeline catches it automatically and converts it into a clean JSON error response.
How It Works
Luau doesn't have a throw keyword, but calling error() achieves the exact same result: it halts execution immediately and bubbles up to Mayari's request handler.
local common = require("common")
local exception = common.exception
local Profile = {}
type ReqParam = {
params: { id: string }
}
--@Guard(Auth)
function Profile.Get(req: IRequest<ReqParam>)
local user = findUser(req.params.id)
if not user then
-- Halts execution and responds with a 404
error(exception.NotFound("User does not exist"))
end
return response.json(user)
end
return ProfileCustom Error Messages
Every built-in exception accepts an optional custom message. If omitted, Mayari uses a standard default message:
-- Sends default message: "Forbidden"
error(exception.Forbidden())
-- Sends custom message: "You don't have permission to perform this action"
error(exception.Forbidden("You don't have permission to perform this action"))Built-in Exceptions Reference
4xx Client Errors
| Exception Function | Status Code | Default Message |
|---|---|---|
exception.BadRequest(msg?) | 400 | Bad Request |
exception.Unauthorized(msg?) | 401 | Unauthorized |
exception.Forbidden(msg?) | 403 | Forbidden |
exception.NotFound(msg?) | 404 | Not Found |
exception.Conflict(msg?) | 409 | Conflict |
exception.TooManyRequests(msg?) | 429 | Too Many Requests |
5xx Server Errors
| Exception Function | Status Code | Default Message |
|---|---|---|
exception.InternalServerError(msg?) | 500 | Internal Server Error |
exception.BadGateway(msg?) | 502 | Bad Gateway |
exception.ServiceUnavailable(msg?) | 503 | Service Unavailable |
Custom HTTP Status Codes
If you need an HTTP status code that isn't listed in the built-in helpers, use exception.HttpException() directly:
local common = require("common")
local exception = common.exception
-- Custom 418 I'm a Teapot response
error(exception.HttpException(418, "I'm a teapot"))Note: Both the status code and message parameters are required when calling
HttpException.
Key Things to Remember
- Immediate Halt: Calling
error()stops code execution instantly, no subsequent code in that handler or middleware will execute. - Request Context: Exceptions must be thrown inside the request pipeline (handlers/middlewares) to be transformed into HTTP responses.
- JSON Format: Mayari formats exceptions as JSON responses automatically (e.g.
{ "error": "User does not exist" }).