You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/how-to/resource-routes.md
+59Lines changed: 59 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -65,3 +65,62 @@ export function action(_: Route.ActionArgs) {
65
65
});
66
66
}
67
67
```
68
+
69
+
## Return Types
70
+
71
+
Resource Routes are flexible when it comes to the return type - you can return [`Response`][Response] instances or [`data()`][data] objects. A good general rule of thumb when deciding which type to use is:
72
+
73
+
- If you're using resource routes intended for external consumption, return `Response` instances
74
+
- Keeps the resulting response encoding explicit in your code rather than having to wonder how React Router might convert `data() -> Response` under the hood
75
+
- If you're accessing resource routes from [fetchers][fetcher] or [`<Form>`][form] submissions, return `data()`
76
+
- Keeps things consistent with the loaders/actions in your UI routes
77
+
- Allows you to stream promises down to your UI through `data()`/[`Await`][await]
78
+
79
+
## Error Handling
80
+
81
+
Throwing an `Error` from Resource route (or anything other than a `Response`/`data()`) will trigger [`handleError`][handleError] and result in a 500 HTTP Response:
82
+
83
+
```tsx
84
+
exportfunction action() {
85
+
let db =awaitgetDb();
86
+
if (!db) {
87
+
// Fatal error - return a 500 response and trigger `handleError`
88
+
thrownewError("Could not connect to DB");
89
+
}
90
+
// ...
91
+
}
92
+
```
93
+
94
+
If a resource route generates a `Response` (via `new Response()` or `data()`), it is considered a successful execution and will not trigger `handleError` because the API has successfully produced a Response for the HTTP request. This applies to thrown responses as well as returned responses with a 4xx/5xx status code. This behavior aligns with `fetch()` which does not return a rejected promise on 4xx/5xx Responses.
[Error Boundaries][error-boundary] are only applicable when a resource route is accessed from a UI, such as from a [`fetcher`][fetcher] call or a [`<Form>`][form] submission. If you `throw` from your resource route in these cases, it will bubble to the nearest `ErrorBoundary` in the UI.
0 commit comments