middleware-pretty-error.ts 1011 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import type { Middleware } from "./common";
  2. // A middleware has to be a function of type Middleware
  3. const prettyError: Middleware = async (request, env, _ctx, middlewareCtx) => {
  4. try {
  5. const response = await middlewareCtx.next(request, env);
  6. return response;
  7. } catch (e: any) {
  8. const html = `
  9. <!DOCTYPE html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  14. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  15. <title>Error 🚨</title>
  16. <style>
  17. pre {
  18. margin: 16px auto;
  19. max-width: 600px;
  20. background-color: #eeeeee;
  21. border-radius: 4px;
  22. padding: 16px;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <pre>${e.stack}</pre>
  28. </body>
  29. </html>
  30. `;
  31. return new Response(html, {
  32. status: 500,
  33. headers: { "Content-Type": "text/html;charset=utf-8" },
  34. });
  35. }
  36. };
  37. export default prettyError;