@@ -21,7 +21,9 @@ import { MiddlewareContext } from 'commandkit';
21
21
22
22
export function beforeExecute(ctx : MiddlewareContext ) {
23
23
// This function will be executed before the command is executed
24
- console .log (` User ${ctx .interaction .user .id } is about to execute a command ` );
24
+ console .log (
25
+ ` User ${ctx .interaction .user .id } is about to execute a command ` ,
26
+ );
25
27
}
26
28
27
29
export function afterExecute(ctx : MiddlewareContext ) {
@@ -52,6 +54,49 @@ export function beforeExecute(ctx: MiddlewareContext) {
52
54
}
53
55
```
54
56
57
+ :::tip
58
+
59
+ You can also use ` stopMiddlewares() ` inside a command function to stop
60
+ any ` afterExecute ` middlewares from running.
61
+
62
+ In addition, you can also use ` stopMiddlewares() ` inside any
63
+ ` afterExecute ` middleware function to stop any remaining middlewares
64
+ from running.
65
+
66
+ :::
67
+
68
+ :::warning
69
+
70
+ Calling ` stopMiddlewares() ` in a try/catch block may lead to
71
+ unexpected behavior.
72
+
73
+ If you still want to use ` stopMiddlewares() ` in a try/catch block, you
74
+ can use the ` isErrorType ` function to check if the error is an
75
+ instance of the ` CommandKitErrorCodes.StopMiddlewares ` error.
76
+
77
+ ``` ts title="src/app/commands/+middleware.ts"
78
+ import type { MiddlewareContext } from ' commandkit' ;
79
+
80
+ export function beforeExecute(ctx : MiddlewareContext ) {
81
+ try {
82
+ // code that may throw an error
83
+
84
+ stopMiddlewares (); // conditionally stop the middleware chain
85
+ } catch (error ) {
86
+ if (isErrorType (error , CommandKitErrorCodes .StopMiddlewares )) {
87
+ // if stopMiddlewares() is called in the try block, throw it so CommandKit can stop the middleware chain
88
+ throw error ;
89
+ }
90
+
91
+ // this means that the code threw the error, and stopMiddlewares() was not called
92
+ // the rest of the middlewares will be executed as normal
93
+ console .error (error );
94
+ }
95
+ }
96
+ ```
97
+
98
+ :::
99
+
55
100
## Middleware types
56
101
57
102
### Directory-scoped middleware
@@ -66,7 +111,9 @@ import type { MiddlewareContext } from 'commandkit';
66
111
export function beforeExecute(ctx : MiddlewareContext ) {
67
112
// This middleware will run before any moderation command
68
113
if (! ctx .interaction .member .permissions .has (' KickMembers' )) {
69
- throw new Error (' You need moderation permissions to use this command' );
114
+ throw new Error (
115
+ ' You need moderation permissions to use this command' ,
116
+ );
70
117
}
71
118
}
72
119
```
0 commit comments