日本語

“Bun.serve: Customizing Error Pages with the error Handler”

​​Bun​curl,HTTP,TypeScript

In Bun.serve, the error handler decides the page returned when an exception is thrown in a handler. You can also look at the type of error and return different pages: a 500 error page, a 404 "page not found", or a 503 for maintenance.

Use this when you want custom error pages (500 or 404) or a maintenance page on your own server. I checked the response status and body with curl in a test environment.

Note

The test environment was Ubuntu 24.04 (x86_64), Bun 1.4.4, and curl 8.5.0. I checked the pages by opening them in Chromium at a smartphone-width viewport. I did not test HTTPS, errors inside WebSocket, or a server bundled into one file with bun build --compile. The official docs are linked to the files for the version I tested (tag bun-v1.4.4) on GitHub.

Returning a 500 page with the error handler

By default, when an exception occurs, the response in development mode is an HTML error screen with source code, and in production mode (NODE_ENV=production) it is the short string Something went wrong!. For the development-mode screen, see the article on setting up a small web server with Bun.serve.

To change this response to your own page, pass error to Bun.serve and return a Response from it (the official docs on the error callback). In the example below, public/500.html is read with Bun.file() and returned.

ts
const server = Bun.serve({
  port: 3000,
  routes: {
    "/boom": () => {
      throw new Error("ここで失敗しました");
    },
    "/async-boom": async () => {
      await Bun.sleep(10);
      throw new Error("await のあとで失敗しました");
    },
  },
  error(error) {
    console.log(`error handler: ${String(error)}`);
    return new Response(Bun.file("public/500.html"), {
      status: 500,
      headers: { "Content-Type": "text/html; charset=utf-8" },
    });
  },
});

In the test, the 500, 404, and 503 pages and the /api wrapper code below were combined into one server.ts and run. The test read the port number from the environment variable PORT, but the article shows it fixed as 3000. Requesting /boom returned status 500 with the contents of 500.html (only the beginning of the body is shown). An exception thrown after await in an async handler also returned the same page.

text
$ curl -sS -i localhost:3000/boom
HTTP/1.1 500 Internal Server Error
Content-Type: text/html; charset=utf-8
content-length: 559

<!doctype html>
<html lang="ja">
...
<h1>ただいま表示できません</h1>

When opened in a browser, it looks like this. The server was started in development mode, but the screen with source code did not appear.

Custom 500 error page with a light blue background. The heading is in Japanese (meaning "Unable to display right now"), followed by a sentence in Japanese (meaning "An error occurred on the server. Please try again later.") and a link in Japanese (meaning "Back to the top page").
The custom 500 page shown when /boom was opened (smartphone width)

Starting the server with NODE_ENV=production also returned the same 500.html. The error handler is called in both development and production modes. The server log shows the thrown error, for example error handler: Error: ここで失敗しました.

Splitting pages for 404 and 503 by error type

The error handler receives the thrown error as is. So if you create an error class that carries a status and tell the cases apart with instanceof, you can return different pages.

ts
// errors.ts
export class HttpError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = "HttpError";
  }
}
ts
import { HttpError } from "./errors.ts";

// A short HTML page returned for 404 and 503
const page = (status: number, title: string) =>
  new Response(
    `<!doctype html><html lang="ja"><meta charset="utf-8"><title>${title}</title><h1>${status} ${title}</h1></html>\n`,
    { status, headers: { "Content-Type": "text/html; charset=utf-8" } },
  );

const server = Bun.serve({
  port: 3000,
  routes: {
    "/items/:id": (req) => {
      if (req.params.id !== "1") throw new HttpError(404, `item ${req.params.id} はありません`);
      return new Response("item 1\n");
    },
    "/maintenance": () => {
      throw new HttpError(503, "メンテナンス中です");
    },
  },
  // Requests that do not match any route
  fetch() {
    return page(404, "ページが見つかりません");
  },
  error(error) {
    if (error instanceof HttpError && error.status === 404) {
      return page(404, "ページが見つかりません");
    }
    if (error instanceof HttpError && error.status === 503) {
      const res = page(503, "メンテナンス中です");
      res.headers.set("Retry-After", "600");
      return res;
    }
    return new Response(Bun.file("public/500.html"), {
      status: 500,
      headers: { "Content-Type": "text/html; charset=utf-8" },
    });
  },
});

/items/2 returned 404, and /maintenance returned 503 with a Retry-After header.

text
$ curl -sS -i localhost:3000/items/2
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=utf-8
Content-Length: 155

<!doctype html><html lang="ja"><meta charset="utf-8"><title>ページが見つかりません</title><h1>404 ページが見つかりません</h1></html>
$ curl -sS -i localhost:3000/maintenance
HTTP/1.1 503 Service Unavailable
Content-Type: text/html; charset=utf-8
Retry-After: 600
Content-Length: 143

<!doctype html><html lang="ja"><meta charset="utf-8"><title>メンテナンス中です</title><h1>503 メンテナンス中です</h1></html>

Paths that are not written in routes are not exceptions, so they do not reach the error handler. As described in the official docs on the fetch handler, requests that match no route go to fetch. In the example above, a request to /no-such-page also returned the same 404 page from fetch.

In a server started with only routes and no fetch, a request to a path with no match returned a 404 with an empty body (Content-Length: 0). The error handler was not called in this case either. To show a 404 page, write fetch.

Forgetting status returns 200

The Response returned from the error handler is sent to the client as is. The status is not automatically changed to 500.

When error returned new Response("no status: ...") without status, the status was 200 even though an exception occurred. This was the same in development and production modes.

text
$ curl -sS -i localhost:3000/boom
HTTP/1.1 200 OK
content-type: text/plain;charset=utf-8
Content-Length: 39

no status: ここで失敗しました
Warning

Always set status on the Response you return from the error handler. If it stays 200, browsers and monitoring tools will treat the error page as a normal page.

When the error handler does not return a Response

I changed how the error handler was written and compared what was returned. The handler type (the definition of error in serve.d.ts) also allows returning nothing, in addition to a Response.

How the error handler is written Development mode Production mode
Not written 500, HTML with source code 500, Something went wrong!
Returns a Response with status: 500 500, the returned content 500, the returned content
Made async, returns a Response after await 500, the returned content 500, the returned content
Returns a Response without status 200, the returned content 200, the returned content
Returns nothing (only logs) 500, HTML with source code 500, Something went wrong!
Throws an exception inside the error handler 500, HTML with source code 500, Something went wrong!

When nothing is returned, or when an exception occurs inside the error handler, the response went back to the same one you get when error is not written. In this case, in development mode, the screen with source code is returned to the requester even though error is written. When you write code in error that can fail, such as building a template, make sure you can still return a fixed Response at the end.

The error handler does not receive the request

The error handler receives only one argument. this was the same server object returned by Bun.serve(). The request URL and Accept header cannot be seen from inside error.

So if you want to change the response based on the request, for example JSON for paths under /api and HTML for everything else, you cannot do it with error alone. In the test, I wrapped the handler for an /api route in a wrapper and caught exceptions there.

ts
// Wrapper that returns errors as JSON, only for /api routes
const api =
  (handler: (req: Bun.BunRequest) => Response | Promise<Response>) =>
  async (req: Bun.BunRequest) => {
    try {
      return await handler(req);
    } catch (e) {
      const status = e instanceof HttpError ? e.status : 500;
      console.log(`api error: ${new URL(req.url).pathname} ${String(e)}`);
      return Response.json({ error: status === 500 ? "internal error" : String((e as Error).message) }, { status });
    }
  };

Use it in routes like this: "/api/items/:id": api((req) => { ... }). The wrapper turns exceptions thrown inside it into JSON, so they never reach the error handler. The log can also show which path failed.

text
$ curl -sS -i localhost:3000/api/items/2
HTTP/1.1 404 Not Found
Content-Type: application/json;charset=utf-8
Content-Length: 21

{"error":"not found"}
$ curl -sS -i localhost:3000/api/items/boom
HTTP/1.1 500 Internal Server Error
Content-Type: application/json;charset=utf-8
Content-Length: 26

{"error":"internal error"}
text
api error: /api/items/2 HttpError: not found
api error: /api/items/boom Error: DB につながりません

When a non-Error value is thrown

In the type, the argument of error is ErrorLike, which extends Error (the definition of ErrorLike in bun.d.ts). However, when a route handler threw a string, such as throw "文字列を throw", the string arrived as is. typeof was string, instanceof Error was false, and error.message was undefined. For logs, using String(error) instead of error.message shows the content in either case.

Errors after the response has started cannot become a page

I also tested a response sent a little at a time with a ReadableStream, where the stream errors partway through. I called controller.error() after sending the first line.

text
$ curl -sS -i localhost:3000/stream
curl: (56) Recv failure: Connection reset by peer
HTTP/1.1 200 OK
Transfer-Encoding: chunked

途中まで送った

The status 200 and the headers had already been sent, so the response could not switch to an error page. The error handler was not called either, and the connection was just cut (curl's exit code was 56). Finish any work needed for an error page before you return the response.

​Posted by 86