Skip to content

Error Handling

David Ciulla edited this page Nov 7, 2026 · 1 revision

Error Handling

Laravex centralises exception handling in Laravex.Foundation.Exceptions. All unhandled exceptions raised during a request pass through the exception handler, which reports them to configured reporters and renders an appropriate HTTP response.


Overview

The kernel catches every exception that escapes a route handler and delegates to the exception handler:

  1. Report — passes the exception to any registered reporter functions and always writes to the error log via Laravex.Log.Logger.error/2.
  2. Render — produces an Laravex.Http.Response appropriate for the client (HTML or JSON, debug or production).

HTTP Exceptions

Raise an HTTP exception from anywhere in a route handler or controller using the abort/2 controller helper:

abort(403)
abort(404, "Post not found")
abort(401, "Unauthenticated")

This raises Laravex.Http.HttpException. The exception handler maps it to the given status code and a plain message response.

Raise directly when you need more control:

raise Laravex.Http.HttpException, status: 422, message: "Unprocessable content"

Validation Failures

Laravex.Validation.Failed is raised automatically by Laravex.Validation.validate_request/3 and Laravex.Http.FormRequest when validation does not pass. The exception handler gives it special treatment:

  • Web requests — redirects back to the previous URL (Referer header or _previous.url in the session) with errors and old input flashed to the session. The @error Blade directive and old() helper surface them in the form.

  • JSON / AJAX requests — returns a 422 Unprocessable Entity JSON response:

    {
      "message": "The given data was invalid.",
      "errors": {
        "email": ["The email field is required."],
        "name":  ["The name field must be at least 2 characters."]
      }
    }

Model Not Found

Laravex.Database.ModelNotFoundException is mapped to 404 Not Found. Throw it when a database record cannot be located:

raise Laravex.Database.ModelNotFoundException

Status Code Mapping

Exception HTTP Status
Laravex.Http.HttpException The status field
Laravex.Database.ModelNotFoundException 404
Laravex.Validation.Failed 302 redirect (web) / 422 (JSON)
Any other exception 500

Production messages returned to the client for 5xx and common 4xx codes:

Status Message
401 "Unauthenticated."
403 "This action is unauthorized."
404 "Not Found"
419 "Page Expired"
429 "Too Many Attempts."
5xx "Server Error"

Debug Mode

Set app.debug to true (or APP_DEBUG=true) to enable the debug exception page. In debug mode:

  • HTML — a dark-themed page shows the full exception message and formatted stacktrace.
  • JSON — the response includes "exception" (exception module name) and "debug" (formatted stacktrace) fields.

Never enable app.debug in production. The debug page may expose internal implementation details.


JSON vs HTML Rendering

The handler renders JSON when any of the following are true:

  • The request's Accept header includes application/json or +json.
  • The request has X-Requested-With: XMLHttpRequest.
  • A custom should_render_json_when function (see below) returns true.

Otherwise it renders an HTML response.


Custom Reporters

Register additional reporter functions in bootstrap/app.ex using Laravex.Foundation.Exceptions.reportable/2:

exceptions =
  Laravex.Foundation.Exceptions.new()
  |> Laravex.Foundation.Exceptions.reportable(fn error ->
    MyErrorTracker.capture(Exception.message(error))
  end)

Each reporter receives the exception struct. Errors inside reporters are silently swallowed so a failing reporter never breaks the response cycle.

The built-in reporter always calls Laravex.Log.Logger.error/2, writing to the configured log channel regardless of whether custom reporters are present.


Custom JSON Detection

Override the JSON-vs-HTML decision with should_render_json_when/2:

exceptions =
  Laravex.Foundation.Exceptions.new()
  |> Laravex.Foundation.Exceptions.should_render_json_when(fn request ->
    String.starts_with?(request.path, "/api/")
  end)

404 Responses

Requests that do not match any route return a 404 without going through the exception handler. For JSON/AJAX requests or paths starting with api/, the response is:

{"message": "Not Found"}

For HTML requests, a minimal HTML page is returned.


Related

  • Logging — how exceptions are written to the log
  • Validation — Laravex.Validation.Failed and Laravex.Validation.Error
  • Responses — abort/2, Laravex.Http.HttpException

Clone this wiki locally