@@ -19,18 +19,22 @@ Elysia catches all the errors thrown in the handler, classifies the error code,
19
19
20
20
``` typescript
21
21
new Elysia ()
22
+ .onError (({ code , error }) => {
23
+ return new Response (error .toString ())
24
+ })
22
25
.get (' /' , () => {
23
26
throw new Error (' Server is during maintainance' )
24
27
25
28
return ' unreachable'
26
29
})
27
- .onError (({ code , error }) => {
28
- return new Response (error .toString ())
29
- })
30
30
```
31
31
32
32
With ` onError ` you can catch and transform the error into your custom error message.
33
33
34
+ ::: tip
35
+ It's important that ` onError ` must be call before handler you want to apply
36
+ :::
37
+
34
38
For example, returning custom 404 messages:
35
39
``` typescript
36
40
import { Elysia } from ' elysia'
@@ -50,15 +54,33 @@ new Elysia()
50
54
You can assign error handling method to a scope using [ hook] ( /concept/life-cycle.html#local-hook ) or [ guard] ( /concept/guard.html )
51
55
``` typescript
52
56
app .get (' /' , () => ' Hello' , {
53
- beforeHandle : ({ set , request : { headers } }) => {
57
+ beforeHandle({ set , request : { headers } }) {
54
58
if (! isSignIn (headers )) {
55
59
set .status = 401
56
- return ' Unauthorized'
60
+
61
+ throw new Error (" Unauthorized" )
57
62
}
63
+ },
64
+ error({ error }) {
65
+ return ' Handled'
58
66
}
59
67
})
60
68
```
61
69
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
+
62
84
## Error Code
63
85
Elysia error code consists of:
64
86
- NOT_FOUND
@@ -98,3 +120,35 @@ new Elysia()
98
120
}
99
121
})
100
122
```
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