@@ -9,6 +9,10 @@ import {
99import withMethods , { HTTPMethods } from "./middlewares/with-methods"
1010import withValidation from "./middlewares/with-validation"
1111import { z } from "zod"
12+ import {
13+ AuthMethodDoesNotApplyException ,
14+ UnauthorizedException ,
15+ } from "../nextjs-exception-middleware"
1216
1317type ParamDef = z . ZodTypeAny | z . ZodEffects < z . ZodTypeAny >
1418
@@ -98,36 +102,36 @@ export const createWithRouteSpec: CreateWithRouteSpecFunction = ((
98102 throw new Error ( `Unknown auth type: ${ undefinedAuthType } ` )
99103
100104 const firstAuthMiddlewareThatSucceeds = ( next ) => async ( req , res ) => {
101- let errors : unknown [ ] = [ ]
102- let didAuthMiddlewareThrow = true
103-
104105 const handleMultipleAuthMiddlewareFailures =
105106 spec . onMultipleAuthMiddlewareFailures ??
106107 onMultipleAuthMiddlewareFailures
107108
108109 for ( const [ name , middleware ] of authMiddlewares ) {
110+ let didAuthMiddlewareThrow = true
109111 try {
110112 return await middleware ( ( ...args ) => {
111113 // Otherwise errors unrelated to auth thrown by built-in middleware (withMethods, withValidation) will be caught here
112114 didAuthMiddlewareThrow = false
113115 return next ( ...args )
114116 } ) ( req , res )
115117 } catch ( error : any ) {
116- if ( didAuthMiddlewareThrow ) {
117- error . source_middleware = name
118- errors . push ( error )
118+ if ( error instanceof AuthMethodDoesNotApplyException ) {
119119 continue
120- } else {
121- throw error
122120 }
121+ error . source_middleware = name
122+ if (
123+ handleMultipleAuthMiddlewareFailures &&
124+ didAuthMiddlewareThrow
125+ ) {
126+ handleMultipleAuthMiddlewareFailures ( [ error ] )
127+ }
128+ throw error
123129 }
124130 }
125-
126- if ( handleMultipleAuthMiddlewareFailures && didAuthMiddlewareThrow ) {
127- handleMultipleAuthMiddlewareFailures ( errors )
128- }
129-
130- throw errors [ errors . length - 1 ]
131+ throw new UnauthorizedException ( {
132+ type : "unauthorized" ,
133+ message : "No authentication methods succeeded" ,
134+ } )
131135 }
132136
133137 return wrappers (
0 commit comments