Skip to content

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.

luau
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 Profile

Custom Error Messages ​

Every built-in exception accepts an optional custom message. If omitted, Mayari uses a standard default message:

luau
-- 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 FunctionStatus CodeDefault Message
exception.BadRequest(msg?)400Bad Request
exception.Unauthorized(msg?)401Unauthorized
exception.Forbidden(msg?)403Forbidden
exception.NotFound(msg?)404Not Found
exception.Conflict(msg?)409Conflict
exception.TooManyRequests(msg?)429Too Many Requests

5xx Server Errors ​

Exception FunctionStatus CodeDefault Message
exception.InternalServerError(msg?)500Internal Server Error
exception.BadGateway(msg?)502Bad Gateway
exception.ServiceUnavailable(msg?)503Service 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:

luau
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" }).