Skip to content

Commit cd6da8e

Browse files
committed
📘 doc: custom error message
1 parent 23e02fc commit cd6da8e

File tree

1 file changed

+59
-5
lines changed

1 file changed

+59
-5
lines changed

docs/patterns/error-handling.md

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,22 @@ Elysia catches all the errors thrown in the handler, classifies the error code,
1919

2020
```typescript
2121
new Elysia()
22+
.onError(({ code, error }) => {
23+
return new Response(error.toString())
24+
})
2225
.get('/', () => {
2326
throw new Error('Server is during maintainance')
2427

2528
return 'unreachable'
2629
})
27-
.onError(({ code, error }) => {
28-
return new Response(error.toString())
29-
})
3030
```
3131

3232
With `onError` you can catch and transform the error into your custom error message.
3333

34+
::: tip
35+
It's important that `onError` must be call before handler you want to apply
36+
:::
37+
3438
For example, returning custom 404 messages:
3539
```typescript
3640
import { Elysia } from 'elysia'
@@ -50,15 +54,33 @@ new Elysia()
5054
You can assign error handling method to a scope using [hook](/concept/life-cycle.html#local-hook) or [guard](/concept/guard.html)
5155
```typescript
5256
app.get('/', () => 'Hello', {
53-
beforeHandle: ({ set, request: { headers } }) => {
57+
beforeHandle({ set, request: { headers } }) {
5458
if(!isSignIn(headers)) {
5559
set.status = 401
56-
return 'Unauthorized'
60+
61+
throw new Error("Unauthorized")
5762
}
63+
},
64+
error({ error }) {
65+
return 'Handled'
5866
}
5967
})
6068
```
6169

70+
## Custom Error Message
71+
You can provide custom error message by providing `error`:
72+
```ts
73+
new Elysia()
74+
.post('/', ({ body }) => body, {
75+
body: t.Object({
76+
name: t.String({
77+
error: 'Name is required'
78+
}),
79+
age: t.Number()
80+
})
81+
})
82+
```
83+
6284
## Error Code
6385
Elysia error code consists of:
6486
- NOT_FOUND
@@ -98,3 +120,35 @@ new Elysia()
98120
}
99121
})
100122
```
123+
124+
## Catching all error
125+
To list all error, you can list an error using `error.all`.
126+
127+
```ts
128+
new Elysia()
129+
.post('/', ({ body }) => body, {
130+
body: t.Object({
131+
name: t.String(),
132+
age: t.Number()
133+
}),
134+
error({ code, error }) {
135+
switch (code) {
136+
case 'VALIDATION':
137+
console.log(error.all)
138+
139+
// Find a specific error name (path is OpenAPI Schema compliance)
140+
const name = error.all.find((x) => x.path === '/name')
141+
142+
// If has validation error, then log it
143+
if(name)
144+
console.log(name)
145+
}
146+
}
147+
})
148+
```
149+
150+
With this you can overwrite provide an advance custom error message or monitor an error based on your need.
151+
152+
::: tip
153+
Make sure to narrow down Error code to "Validation" to narrow down error type before using `error.all`
154+
:::

0 commit comments

Comments
 (0)