Skip to content

Commit fa3078c

Browse files
ematipicolilnasy
andauthoredDec 19, 2023
fix: handle middleware loading error (#9458)
* fix: handle middleware loading error * remove the try/catch * rethrow error * Update packages/astro/src/core/middleware/loadMiddleware.ts Co-authored-by: Arsh <69170106+lilnasy@users.noreply.github.com> --------- Co-authored-by: Arsh <69170106+lilnasy@users.noreply.github.com>
1 parent 429be8c commit fa3078c

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed
 

‎.changeset/selfish-rings-occur.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Correctly handle the error in case the middleware throws a runtime error

‎packages/astro/src/core/errors/errors-data.ts

+20
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,26 @@ export const LocalsNotAnObject = {
780780
hint: 'If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`.',
781781
} satisfies ErrorData;
782782

783+
/**
784+
* @docs
785+
* @description
786+
* Thrown in development mode when middleware throws an error while attempting to loading it.
787+
*
788+
* For example:
789+
* ```ts
790+
* import {defineMiddleware} from "astro:middleware";
791+
* throw new Error("Error thrown while loading the middleware.")
792+
* export const onRequest = defineMiddleware(() => {
793+
* return "string"
794+
* });
795+
* ```
796+
*/
797+
export const MiddlewareCantBeLoaded = {
798+
name: 'MiddlewareCantBeLoaded',
799+
title: "Can't load the middleware.",
800+
message: 'The middleware thrown an error while Astro was trying to loading it.',
801+
} satisfies ErrorData;
802+
783803
/**
784804
* @docs
785805
* @see
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { ModuleLoader } from '../module-loader/index.js';
22
import { MIDDLEWARE_MODULE_ID } from './vite-plugin.js';
3+
import { MiddlewareCantBeLoaded } from '../errors/errors-data.js';
4+
import { AstroError } from '../errors/index.js';
35

46
/**
57
* It accepts a module loader and the astro settings, and it attempts to load the middlewares defined in the configuration.
@@ -8,9 +10,9 @@ import { MIDDLEWARE_MODULE_ID } from './vite-plugin.js';
810
*/
911
export async function loadMiddleware(moduleLoader: ModuleLoader) {
1012
try {
11-
const module = await moduleLoader.import(MIDDLEWARE_MODULE_ID);
12-
return module;
13-
} catch {
14-
return void 0;
13+
return await moduleLoader.import(MIDDLEWARE_MODULE_ID);
14+
} catch (error: any) {
15+
const astroError = new AstroError(MiddlewareCantBeLoaded, undefined, { cause: error });
16+
throw astroError;
1517
}
1618
}

0 commit comments

Comments
 (0)
Please sign in to comment.