|
| 1 | +<!-- |
| 2 | +SPDX-FileCopyrightText: 2020 Zach Daniel |
| 3 | +
|
| 4 | +SPDX-License-Identifier: MIT |
| 5 | +--> |
| 6 | + |
| 7 | +# Errors |
| 8 | + |
| 9 | +AshJsonApi converts Ash errors into [JSON:API error objects](https://jsonapi.org/format/#errors). This topic covers how that conversion works, how to customize it, and the available configuration options. |
| 10 | + |
| 11 | +## Error Format |
| 12 | + |
| 13 | +Every error response follows the JSON:API error object format: |
| 14 | + |
| 15 | +```json |
| 16 | +{ |
| 17 | + "errors": [ |
| 18 | + { |
| 19 | + "id": "a1b2c3d4-...", |
| 20 | + "status": "422", |
| 21 | + "code": "invalid_attribute", |
| 22 | + "title": "InvalidAttribute", |
| 23 | + "detail": "must be present", |
| 24 | + "source": { |
| 25 | + "pointer": "/data/attributes/name" |
| 26 | + } |
| 27 | + } |
| 28 | + ] |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +## The `AshJsonApi.ToJsonApiError` Protocol |
| 33 | + |
| 34 | +AshJsonApi uses the `AshJsonApi.ToJsonApiError` protocol to convert Ash exceptions into `AshJsonApi.Error` structs. Built-in implementations are provided for common Ash errors such as `Ash.Error.Changes.InvalidChanges`, `Ash.Error.Query.NotFound`, `Ash.Error.Forbidden.Policy`, and others. |
| 35 | + |
| 36 | +If your application raises a custom Ash exception and you want it to produce a specific JSON:API error, implement the protocol: |
| 37 | + |
| 38 | +```elixir |
| 39 | +defimpl AshJsonApi.ToJsonApiError, for: MyApp.Errors.PaymentRequired do |
| 40 | + def to_json_api_error(error) do |
| 41 | + %AshJsonApi.Error{ |
| 42 | + id: Ash.UUID.generate(), |
| 43 | + status_code: 402, |
| 44 | + code: "payment_required", |
| 45 | + title: "PaymentRequired", |
| 46 | + detail: error.message, |
| 47 | + meta: %{} |
| 48 | + } |
| 49 | + end |
| 50 | +end |
| 51 | +``` |
| 52 | + |
| 53 | +The `AshJsonApi.Error` struct has the following fields: |
| 54 | + |
| 55 | +| Field | Description | |
| 56 | +|---|---| |
| 57 | +| `id` | Unique identifier for this error occurrence | |
| 58 | +| `status_code` | HTTP status code (integer) | |
| 59 | +| `code` | Machine-readable error code string | |
| 60 | +| `title` | Human-readable error title | |
| 61 | +| `detail` | Human-readable explanation specific to this occurrence | |
| 62 | +| `source_pointer` | JSON Pointer to the source of the error (e.g. `/data/attributes/name`) | |
| 63 | +| `source_parameter` | Query parameter that caused the error | |
| 64 | +| `meta` | Arbitrary metadata map | |
| 65 | +| `about` | Link to further information about this error | |
| 66 | +| `log_level` | Log level for this error (default: `:debug`) | |
| 67 | +| `internal_description` | Internal description used for logging, not sent to clients | |
| 68 | + |
| 69 | +## Transforming Errors with `error_handler` |
| 70 | + |
| 71 | +The `error_handler` domain option lets you intercept and transform any `AshJsonApi.Error` struct before it is sent to the client. This is useful for sanitizing error messages, adding metadata, translating error text, or applying any other cross-cutting transformation. |
| 72 | + |
| 73 | +Configure it in your domain as an MFA: |
| 74 | + |
| 75 | +```elixir |
| 76 | +defmodule MyApp.Domain do |
| 77 | + use Ash.Domain, extensions: [AshJsonApi.Domain] |
| 78 | + |
| 79 | + json_api do |
| 80 | + error_handler {MyApp.JsonApiErrorHandler, :handle_error, []} |
| 81 | + end |
| 82 | +end |
| 83 | +``` |
| 84 | + |
| 85 | +The handler receives the `AshJsonApi.Error` struct and a context map, and must return a modified `AshJsonApi.Error` struct: |
| 86 | + |
| 87 | +```elixir |
| 88 | +defmodule MyApp.JsonApiErrorHandler do |
| 89 | + def handle_error(error, _context) do |
| 90 | + # Sanitize internal details from 500 errors |
| 91 | + if error.status_code >= 500 do |
| 92 | + %{error | detail: "An internal error occurred. Please try again later."} |
| 93 | + else |
| 94 | + error |
| 95 | + end |
| 96 | + end |
| 97 | +end |
| 98 | +``` |
| 99 | + |
| 100 | +The context map contains: |
| 101 | + |
| 102 | +| Key | Description | |
| 103 | +|---|---| |
| 104 | +| `:domain` | The domain module handling the request | |
| 105 | +| `:resource` | The resource module associated with the request (may be `nil`) | |
| 106 | + |
| 107 | +### Example: Translating Error Messages |
| 108 | + |
| 109 | +```elixir |
| 110 | +defmodule MyApp.JsonApiErrorHandler do |
| 111 | + def handle_error(error, _context) do |
| 112 | + %{error | detail: MyApp.Gettext.translate_error(error.code, error.detail)} |
| 113 | + end |
| 114 | +end |
| 115 | +``` |
| 116 | + |
| 117 | +### Example: Adding Custom Metadata |
| 118 | + |
| 119 | +```elixir |
| 120 | +defmodule MyApp.JsonApiErrorHandler do |
| 121 | + def handle_error(error, %{domain: domain}) do |
| 122 | + %{error | meta: Map.put(error.meta || %{}, :api_version, "v2")} |
| 123 | + end |
| 124 | +end |
| 125 | +``` |
| 126 | + |
| 127 | +### Example: Context-Specific Handling |
| 128 | + |
| 129 | +```elixir |
| 130 | +defmodule MyApp.JsonApiErrorHandler do |
| 131 | + def handle_error(error, %{resource: resource}) do |
| 132 | + case resource do |
| 133 | + MyApp.PaymentResource -> |
| 134 | + %{error | detail: MyApp.Payments.format_error(error)} |
| 135 | + |
| 136 | + _ -> |
| 137 | + error |
| 138 | + end |
| 139 | + end |
| 140 | +end |
| 141 | +``` |
| 142 | + |
| 143 | +## Configuration Options |
| 144 | + |
| 145 | +### `show_raised_errors?` |
| 146 | + |
| 147 | +By default, if an error is *raised* (i.e. an unexpected exception, not a structured Ash error), AshJsonApi returns a generic error message with only a UUID for reference. This prevents leaking internal implementation details. |
| 148 | + |
| 149 | +Set `show_raised_errors? true` to include the full exception in the response — useful during development: |
| 150 | + |
| 151 | +```elixir |
| 152 | +json_api do |
| 153 | + show_raised_errors? true |
| 154 | +end |
| 155 | +``` |
| 156 | + |
| 157 | +### `log_errors?` |
| 158 | + |
| 159 | +Controls whether errors are logged. Defaults to `true`. |
| 160 | + |
| 161 | +```elixir |
| 162 | +json_api do |
| 163 | + log_errors? false |
| 164 | +end |
| 165 | +``` |
| 166 | + |
| 167 | +### Policy Breakdown Details |
| 168 | + |
| 169 | +By default, authorization failures return a generic "forbidden" message. To include a breakdown of which policies failed (useful for debugging), set this in your application config: |
| 170 | + |
| 171 | +```elixir |
| 172 | +# config/dev.exs |
| 173 | +config :ash_json_api, :policies, show_policy_breakdowns?: true |
| 174 | +``` |
| 175 | + |
| 176 | +> **Warning:** Do not enable this in production, as it may expose details about your authorization logic. |
0 commit comments