middleware-miniflare3-json-error.ts 732 B

1234567891011121314151617181920212223242526272829303132
  1. import type { Middleware } from "./common";
  2. interface JsonError {
  3. message?: string;
  4. name?: string;
  5. stack?: string;
  6. cause?: JsonError;
  7. }
  8. function reduceError(e: any): JsonError {
  9. return {
  10. name: e?.name,
  11. message: e?.message ?? String(e),
  12. stack: e?.stack,
  13. cause: e?.cause === undefined ? undefined : reduceError(e.cause),
  14. };
  15. }
  16. // See comment in `bundle.ts` for details on why this is needed
  17. const jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {
  18. try {
  19. return await middlewareCtx.next(request, env);
  20. } catch (e: any) {
  21. const error = reduceError(e);
  22. return Response.json(error, {
  23. status: 500,
  24. headers: { "MF-Experimental-Error-Stack": "true" },
  25. });
  26. }
  27. };
  28. export default jsonError;