Handle Errors

All uncaught error while processing HTTP requests are captured internally and passed into final error handler.

There are exactly two error handlers for one Router.

One is Servest's build-in final error handler. It handles all uncaught errors from middleware 500 (Internal Server error) and finalizes unhandled requests with 404 (Not Found).

Another is custom error handler by user. Below is an example to define global error handler for router.

There can be only one global error handler for one router. If custom error handler is not defined by user, errors are handled by built-in final error handler as default. If defined, errors are passed to it and if not handled by it, errors are passed to final error handler.

// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
import { createRouter } from "https://servestjs.org/@v0.30.0/router.ts";
import { RoutingError } from "https://servestjs.org/@v0.30.0/error.ts";

const router = createRouter();
router.handle("/", async req => {
  throw new Error("error");
});
// Define global error handler for router
router.handleError(async (e, req) => {
  // All uncaught errors and unhandled promise rejections will be here.
  // Do your custom request finalization.
  if (e instanceof RoutingError && e.status === 404) {
    // RoutingError is thrown by router.
    // Typically no middleware responded to request.
    // Custom error page or response can be served here.
    const errorPage = await Deno.open("./public/error.html");
    try {
      await req.respond({
        status: 404,
        headers: new Headers({
          "content-type": "text/html"
        }),
        body: errorPage
      });
    } finally {
      errorPage.close();
    }
  } else {
    await req.respond({
      status: 500,
      body: "Internal Server Error"
    });
  }
});
router.listen(":8899");