@@ -21,7 +21,9 @@ import { MiddlewareContext } from 'commandkit';
2121
2222export function beforeExecute(ctx : MiddlewareContext ) {
2323 // 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+ );
2527}
2628
2729export function afterExecute(ctx : MiddlewareContext ) {
@@ -52,6 +54,49 @@ export function beforeExecute(ctx: MiddlewareContext) {
5254}
5355```
5456
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+
55100## Middleware types
56101
57102### Directory-scoped middleware
@@ -66,7 +111,9 @@ import type { MiddlewareContext } from 'commandkit';
66111export function beforeExecute(ctx : MiddlewareContext ) {
67112 // This middleware will run before any moderation command
68113 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+ );
70117 }
71118}
72119```
0 commit comments