laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# Error Handling

- [Introduction](#introduction)
- [Debug mode](#debug-mode)
- [Returning errors](#returning-errors)
    - [Defining your own errors](#defining-your-own-errors)
    - [Errors with their own status](#errors-with-their-own-status)
    - [Adding context](#adding-context)
- [HTTP errors](#http-errors)
    - [Aborting when a condition holds](#aborting-when-a-condition-holds)
    - [Headers](#headers)
- [Invalid input](#invalid-input)
- [Failures and expected outcomes](#failures-and-expected-outcomes)
    - [Reporting and carrying on](#reporting-and-carrying-on)
    - [Panics](#panics)
- [Error pages](#error-pages)
- [Customizing the error handler](#customizing-the-error-handler)
    - [Reporting errors](#reporting-errors)
    - [Ignoring errors by type](#ignoring-errors-by-type)
    - [Rendering errors](#rendering-errors)
    - [Adjusting every error response](#adjusting-every-error-response)
    - [Keeping input out of old input](#keeping-input-out-of-old-input)
    - [Errors from packages](#errors-from-packages)
    - [Inspecting errors](#inspecting-errors)
- [Testing errors](#testing-errors)

<a name="introduction"></a>
## Introduction

When you create a new Laravel project, error handling is already configured for you. Whenever a handler returns an error, such as when a requested post doesn't exist or a database query fails, Laravel converts it into an HTTP response: JSON for API clients and an error page for browsers. When an error is a server [failure](#failures-and-expected-outcomes), Laravel also logs it so you can investigate what went wrong.

Whenever you need to customize how your application reports or renders errors, configure the error handler with `with_errors` in `src/app.rs`.

<a name="debug-mode"></a>
## Debug mode

The `APP_DEBUG` environment variable controls how much detail Laravel exposes when a server failure occurs. When `APP_DEBUG=true`, browsers receive a detailed debug page showing the error, where it happened, its chain of causes, and the incoming request, while JSON responses include the error's type, file, and line.

When `APP_DEBUG=false`, Laravel replaces failure messages with `"Server Error"` so internal messages written for your logs never leak to users. The only exception is a failure raised intentionally for clients with `abort_with`, such as `laravel::abort_with(503, "We're upgrading. Back in a minute.")`, which includes that message in JSON responses.

New applications enable debug mode in `.env` for local development:

```ini
APP_DEBUG=true
```

> [!WARNING]
> Always set `APP_DEBUG` to `false` in production. The debug page exposes stack traces, request data, and internal error messages to your users.

<a name="returning-errors"></a>
## Returning errors

Handlers and middleware that can fail return `laravel::Result`. Using `?`, any type that implements `std::error::Error` converts automatically into `laravel::Error`, as does an `anyhow::Error` from a library. Unless the error specifies a status code, Laravel responds with `500 Internal Server Error`:

```rust
use laravel::prelude::*;

use crate::models::User;

pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {
    let user = User::find_or_fail(id).await?;

    Ok(Json(user))
}
```

If the database query fails, `find_or_fail` returns a `500` error. If no user matches the given ID, it returns a `404` because `ModelNotFound` carries a [status of `404`](#errors-with-their-own-status).

When you want to return a one-off error without defining a custom error type, create one from a message with `laravel::Error::msg`:

```rust
pub fn header_row(contents: &str) -> laravel::Result<&str> {
    let Some(header) = contents.lines().next() else {
        return Err(laravel::Error::msg("the import file has no header row"));
    };

    Ok(header)
}
```

Laravel treats this error as a `500` [failure](#failures-and-expected-outcomes), logging the message while showing `"Server Error"` to users outside debug mode. If you want the message returned to the client instead, use `laravel::abort_with(500, message)`.

<a name="defining-your-own-errors"></a>
### Defining your own errors

An error type is any struct or enum that implements `std::error::Error`. New applications include the [thiserror](https://docs.rs/thiserror) crate, which derives the implementation for you. The `#[error("...")]` attribute defines the error's message and may interpolate fields by name or position:

```rust
#[derive(Debug, thiserror::Error)]
pub enum PaymentError {
    #[error("The card was declined: {reason}")]
    Declined { reason: String },

    #[error("The amount {0} is below the minimum")]
    BelowMinimum(u64),

    #[error("The receipt couldn't be saved")]
    Receipt(#[from] std::io::Error),
}
```

Adding `#[from]` lets `?` convert the inner error into your variant automatically, so an `std::io::Error` becomes `PaymentError::Receipt` and keeps the original `io::Error` as its cause:

```rust
pub fn save_receipt(path: &str, contents: &str) -> Result<(), PaymentError> {
    std::fs::write(path, contents)?;

    Ok(())
}
```

<a name="errors-with-their-own-status"></a>
### Errors with their own status

To associate an HTTP status code with an error type, such as `409 Conflict` for a double booking, derive `Status` and add `#[status(..)]`. Returning that error from a handler with `?` then responds with that status:

```rust
use laravel::errors::Status;

#[derive(Debug, thiserror::Error, Status)]
#[error("This time slot is already booked")]
#[status(409)]
pub struct BookingConflict;
```

On an enum, you may give each variant its own status. Any variant without a `#[status(..)]` attribute defaults to `500`:

```rust
use laravel::errors::Status;

#[derive(Debug, thiserror::Error, Status)]
pub enum PaymentError {
    #[error("The card was declined: {reason}")]
    #[status(402)]
    Declined { reason: String },

    #[error("The amount {0} is below the minimum")]
    #[status(422)]
    BelowMinimum(u64),

    #[error("The receipt couldn't be saved")]
    Receipt(#[from] std::io::Error),
}
```

The status may be a numeric code such as `402` or a `StatusCode` constant such as `StatusCode::PAYMENT_REQUIRED`.

You can't derive `Status` on an error type defined in another crate. Instead, map its status inside `with_errors` in `src/app.rs`. Mapping a type there also overrides a derived status, such as one from a package:

```rust
use laravel::prelude::*;

Application::configure()
    .with_errors(|errors, _| {
        errors.status::<laravel::db::sqlx::Error>(503);
    })
```

To assign a status to a single error at the point you return it, wrap it with `laravel::Error::new`:

```rust
return Err(laravel::Error::new(409, BookingConflict));
```

<a name="adding-context"></a>
### Adding context

Low-level errors such as `"No such file or directory"` rarely explain what your application was doing when they happened. To attach context for your logs, call `context` or `with_context` on any `Result`. The `ErrorContext` trait is included in the [prelude](prelude.md):

```rust
use laravel::prelude::*;

let license = tokio::fs::read_to_string("license.txt")
    .await
    .context("the license can't be read")?;

let post = Post::find_or_fail(id)
    .await
    .with_context(|| format!("the post `{id}` can't be loaded"))?;
```

The context becomes the outer message and the original error becomes its cause, so your logs read ``the post `42` can't be loaded: no such table: posts``. The error keeps its original type, caller location, and status code, so a `404` with context is still a `404` and JSON logs still report the underlying error type rather than `anyhow::Error`.

Context is meant for developers, not end users. Laravel logs and reports it and displays it on the [debug page](#debug-mode), but omits it from normal responses so you can safely include IDs or tenant names. A `404` with context still responds with `"Not Found"`. To customize the message users see, customize your [error pages](#error-pages).

<a name="http-errors"></a>
## HTTP errors

Sometimes a handler needs to stop and return an HTTP status directly, such as `404 Not Found` or `403 Forbidden`. The `abort!` macro returns from the handler immediately using the status code and optional message you provide. For example, if your `User` model has a `banned` field, this handler hides profiles of banned users:

```rust
use laravel::prelude::*;

use crate::models::User;

pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {
    let user = User::find_or_fail(id).await?;

    if user.banned {
        laravel::abort!(404);
    }

    Ok(Json(user))
}
```

The status may be a number or a `StatusCode`, and the optional message accepts `format!` arguments:

```rust
laravel::abort!(StatusCode::FORBIDDEN);

laravel::abort!(409, "The name `{}` is taken.", user.name);
```

To turn an `Option::None` into an HTTP error, call `or_abort`. Its `OrAbort` trait is included in the [prelude](prelude.md):

```rust
let user = User::find(id).await?.or_abort(404)?;
```

<a name="aborting-when-a-condition-holds"></a>
### Aborting when a condition holds

You may abort conditionally with `abort_if` (which fails when the condition is `true`) and `abort_unless` (which fails when it's `false`). For example, if your `Post` model has a `user_id` field, this handler allows only the post's author to edit it:

```rust
use laravel::prelude::*;
use laravel::view::View;

use crate::models::{Post, User};

pub async fn edit(
    user: Authenticated<User>,
    Params(id): Params<i64>,
) -> laravel::Result<View> {
    let post = Post::find_or_fail(id).await?;

    laravel::abort_if(post.user_id != user.id, 403)?;

    Ok(view("posts.edit", data! { post }))
}
```

For reusable permission checks across multiple handlers, a [policy](authorization.md) is usually clearer than repeating conditions in each handler.

<a name="headers"></a>
### Headers

Any error may carry response headers, such as `Retry-After` on a `429 Too Many Requests` response, and Laravel includes them whether the error renders as JSON or HTML. The `abort` and `abort_with` functions build an `Error` without returning it immediately, so you may attach headers before returning:

```rust
return Err(laravel::abort(429).with_header("retry-after", "60"));
```

<a name="invalid-input"></a>
## Invalid input

Validation rules catch most invalid input before your handler runs. When your handler discovers a problem that rules can't express, such as an email address that has already been invited, return an `InvalidInput` error with a message for each invalid field using the `invalid!` macro:

```rust
use laravel::validation::invalid;

invalid!(email => "That email is already invited.");
```

Laravel treats `InvalidInput` as a failed [validation](validation.md#adding-errors-after-validation). For browser form submissions, Laravel redirects back to the form with the errors and old input. For API requests, Laravel responds with `422 Unprocessable Content` and a JSON payload listing each field's errors:

```json
{
    "message": "That email is already invited.",
    "errors": {
        "email": ["That email is already invited."]
    }
}
```

To learn more about defining validation rules and returning validation errors, check out the [validation guide](validation.md).

<a name="failures-and-expected-outcomes"></a>
## Failures and expected outcomes

Laravel handles errors differently depending on their HTTP status code:

- **Failures** have a `5xx` server status, such as `500` or `503`. Laravel reports them by logging the error and passing it to your [reporters](#reporting-errors), and hides their internal message from users unless you raised the error with `abort_with`.
- **Expected outcomes** have any non-`5xx` status, usually a `4xx` client status such as `404`, `403`, or `422`. Laravel doesn't report them. JSON responses include the error's message, while HTML error pages display its status.

<a name="reporting-and-carrying-on"></a>
### Reporting and carrying on

Sometimes a failure shouldn't break the entire request. For example, a product page can still render without its recommendations, even though you want to know that the recommendation service is down. Call `laravel::report` to log and report the error while your handler continues.

This handler fetches recommendations with the [HTTP client](http-client.md). If the request fails, it reports the error and renders the page with an empty list:

```rust
use laravel::http::client;
use laravel::prelude::*;
use laravel::view::View;

use crate::models::Product;

pub async fn show(Params(id): Params<i64>) -> laravel::Result<View> {
    let product = Product::find_or_fail(id).await?;

    let recommendations = client::get(format!(
        "https://recommendations.example.com/products/{id}",
    ))
        .ensure_successful()
        .await
        .and_then(|response| response.json::<Vec<serde_json::Value>>())
        .unwrap_or_else(|error| {
            laravel::report(error);

            Vec::new()
        });

    Ok(view("products.show", data! { product, recommendations }))
}
```

`laravel::report` logs the error with the request's [context](logging.md#adding-context) and passes it to your reporters. It skips expected outcomes, so `laravel::report(laravel::abort(404))` does nothing.

<a name="panics"></a>
### Panics

If a handler panics, Laravel catches the panic, [logs](logging.md#errors-and-panics) the file and line where it happened, and renders a `500` response while your application continues serving other requests. Even so, return `Result` errors for failures you anticipate and reserve panics for bugs.

<a name="error-pages"></a>
## Error pages

Requests that [want JSON](requests.md#content-negotiation), along with every request to a route in the `api` group, receive errors as JSON, such as `{ "message": "Not Found" }`. All other requests receive an HTML error page.

In JSON responses, `"message"` comes from the error that set the status code, whether passed to `abort!` or `abort_with`, or defined with `#[error("...")]` on an error type that [derives `Status`](#errors-with-their-own-status):

```rust
laravel::abort!(404, "That post doesn't exist.");
```

For example, returning `BookingConflict` (`409`) produces `"This time slot is already booked"`, even if you attached internal context. A missing model produces `ModelNotFound`'s message naming the model and key, while server failures return `"Server Error"` unless debug mode is enabled or you used `abort_with`.

HTML error pages display the status code and reason phrase, such as `"404 Not Found"` or `"419 Page Expired"`, whether debug mode is on or off. A `403` page displays the error's message instead so a [policy's denial](authorization.md#denying-with-a-message) can explain why access was refused. When debug mode is on, server failures render the debug page instead.

To customize your error pages, create a [view](views.md) named after the status code, such as `resources/views/errors/404.html`. You may also create fallback views at `errors/4xx.html` and `errors/5xx.html` for any status without a dedicated view. Each view receives `status` and `message`:

```html
{% extends "layouts.app" %}

{% block content %}
    <h1>{{ status }}</h1>
    <p>{{ message }}</p>
{% endblock %}
```

If your application uses [Inertia](inertia.md), you may render errors with a frontend page component instead. Return the component's name from your `HandleInertiaRequests` middleware's `error_page` method. The component receives an `error` prop holding `status` and `message`, along with your shared props. New applications include an `Error` page component you can customize:

```rust
use laravel::inertia;

impl inertia::Middleware for HandleInertiaRequests {
    fn error_page(&self) -> Option<&str> {
        Some("Error")
    }
}
```

To learn more about setting titles and other metadata on error pages, check out the head metadata guide's section on [error pages](head.md#error-pages).

<a name="customizing-the-error-handler"></a>
## Customizing the error handler

To customize how your application reports and renders errors, call `with_errors` in `src/app.rs`. Its closure receives the `Errors` builder and your application's configuration, so you may conditionally register reporters when an error tracker's key is configured:

```rust
use laravel::prelude::*;

Application::configure()
    .with_errors(|errors, config| {
        // ...
    })
```

<a name="reporting-errors"></a>
### Reporting errors

Laravel logs every server failure automatically. To also send failures of a specific type to an external service, register a reporter for that type inside `with_errors`:

```rust
errors.report(|error: &PaymentError| {
    // Send the error to your error tracker...
});
```

To report every failure regardless of its type, use `report_all`. Its closure receives `laravel::Error`, which you may [inspect](#inspecting-errors):

```rust
errors.report_all(|error| {
    // Send every failure to your error tracker...
});
```

If your error tracker integrates with `tracing`, such as Sentry, you don't need a custom reporter. Laravel logs every failure at the `error` level, so [adding the tracker's tracing layer](logging.md#sentry) captures them automatically.

<a name="ignoring-errors-by-type"></a>
### Ignoring errors by type

To keep expected failures out of your logs and reporters, ignore their type with `dont_report`. For example, an application that already retries failed calls to a partner API might ignore [HTTP client](http-client.md) errors:

```rust
use laravel::http::client;

errors.dont_report::<client::Error>();
```

Ignored errors still render responses as usual.

<a name="rendering-errors"></a>
### Rendering errors

To render a specific error type your own way, register a renderer with `render`. Your closure receives the error, the request, and the error's status code, and returns `Option<Response>`. Returning `None` falls back to Laravel's default rendering.

Laravel sends whatever response your renderer returns, so include the status code or the response will be `200 OK`. Check `request.wants_json()` when your renderer serves both API clients and browsers. For example, this renderer returns the decline reason as JSON for API clients and renders an [Inertia page](inertia.md#rendering-an-error-as-a-page) for browsers:

```rust
use laravel::inertia::props;
use serde_json::json;

errors.render(|error: &PaymentError, request, status| {
    let PaymentError::Declined { reason } = error else {
        return None;
    };

    if request.wants_json() {
        let body = json!({
            "message": error.to_string(),
            "reason": reason,
        });

        return Some((status, Json(body)).into_response());
    }

    let page = request
        .inertia()?
        .render("Billing/CardDeclined", props! { reason => reason });

    Some((status, page).into_response())
});
```

<a name="adjusting-every-error-response"></a>
### Adjusting every error response

To modify every rendered error response, register a callback with `respond`. It receives the rendered `Response`, the error, and the request, and returns the response to send. For example, this responder prevents browsers and proxies from caching error pages:

```rust
errors.respond(|response, _error, _request| {
    response.with_header("cache-control", "no-store")
});
```

If your application uses Inertia, you may also use `respond` to redirect users back to their form with a message when a `419` page-expired error occurs. To learn more, check out the Inertia guide's section on [expired pages](inertia.md#expired-pages).

<a name="keeping-input-out-of-old-input"></a>
### Keeping input out of old input

When an invalid form redirects back, Laravel flashes the submitted fields to the session as [old input](validation.md#errors-and-old-input). Laravel never flashes `password`, `password_confirmation`, or `current_password`. To exclude additional sensitive fields, list them with `dont_flash`, using "dot" notation for nested fields:

```rust
errors.dont_flash(["ssn", "card.number", "card.cvc"]);
```

<a name="errors-from-packages"></a>
### Errors from packages

Packages configure their own errors through `app.errors()` in their service provider's `register` method, using the same `Errors` builder as `with_errors`. Your application's `with_errors` runs after every service provider, so your status mappings override a package's for the same error type, and your renderers run first (returning `None` falls back to the package's renderer). To learn more about registering errors in a package, check out the package development guide's section on [errors](packages.md#errors).

<a name="inspecting-errors"></a>
### Inspecting errors

Inside reporters, responders, and tests, you may inspect a `laravel::Error` with these methods:

| Method | Returns |
| --- | --- |
| `status()` | Its status code, such as `StatusCode::PAYMENT_REQUIRED`. |
| `is::<PaymentError>()` | Whether it's a `PaymentError`. |
| `downcast_ref::<PaymentError>()` | The underlying `PaymentError`, if it is one. |
| `chain()` | Its context messages, followed by the error and its causes. |
| `location()` | Where it was created, such as `src/http/handlers/orders.rs:42:31`. |

<a name="testing-errors"></a>
## Testing errors

In [HTTP tests](testing.md), each response retains the error it was rendered from, so you may assert directly on error types rather than matching HTML text. Use `assert_error` to check the rendered error's type, `assert_reported` and `assert_not_reported` to check whether a specific error type was reported (including via `laravel::report`), and `assert_nothing_reported` to verify that no failures were reported at all:

```rust
use laravel::http::client;
use laravel::model::create;
use laravel::testing::prelude::*;

use crate::models::Product;

#[laravel::test]
async fn a_declined_card_is_a_payment_error(app: Application) {
    app.post("/checkout")
        .await
        .assert_payment_required()
        .assert_error::<PaymentError>()
        .assert_nothing_reported();
}

#[laravel::test]
async fn products_show_without_recommendations(app: Application) -> laravel::Result<()> {
    let product = create!(Product { name: "Desk lamp" }).await?;

    let _http = client::fake()
        .with("recommendations.example.com/*", client::failed_connection());

    app.get(format!("/products/{}", product.id))
        .await
        .assert_ok()
        .assert_reported::<client::Error>();

    Ok(())
}
```