Handle Validation Errors

This guide shows you how to handle and respond to validation errors in your Azu application.

Automatic Error Handling

Azu automatically validates requests and raises ValidationError for invalid data:

struct CreateUserEndpoint
  include Azu::Endpoint(CreateUserRequest, UserResponse)

  post "/users"

  def call : UserResponse
    # If validation fails, Azu raises ValidationError automatically
    # The error handler converts it to a 422 response
    UserResponse.new(User.create!(create_user_request))
  end
end

Default Error Response

When validation fails, Azu returns:

{
  "errors": [
    {"field": "name", "message": "can't be blank"},
    {"field": "email", "message": "is invalid"}
  ]
}

With HTTP status 422 Unprocessable Entity.

Custom Error Responses

Create a custom error response format:

Manual Validation Handling

Handle validation manually in your endpoint:

Model Validation Errors

Handle model validation errors:

Custom Error Handler

Create a global error handler for validation errors:

Register the handler:

Collecting All Errors

Ensure all validation errors are collected:

Displaying Errors to Users

For HTML responses, pass errors to templates:

In your template:

Internationalization

Customize error messages:

See Also

Last updated

Was this helpful?