Home > Web Front-end > JS Tutorial > Elegant Error Handling and End to End typesafety with Hono RPC

Elegant Error Handling and End to End typesafety with Hono RPC

Barbara Streisand
Release: 2024-12-25 11:18:11
Original
855 people have browsed it

Elegant Error Handling and End to End typesafety with Hono RPC

I've always had a love-hate relationship with JavaScript's error handling. Its reliance on try-catch blocks and throwing exceptions might work for others, but it definitely frustrates me sometimes.

Consider this typical JavaScript error handling pattern:

async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error.message);
  }
}
Copy after login

That's a lot of code and we still don't know the type of the error.

My opinion is that when dealing with errors, you want to know what caused the error, where it came from, and what type of error it is and handle it right away. Especially when you're in a server environment. For me


The golang way

I prefer to handle errors like how golang handles them, basically error as values.

data, err := getData()
if err != nil {
  // handle error
}
Copy after login

This way you handle the error right away and you don't have to worry about the rest of the code running if there's an error.

Supabase does the same thing with their supabase-js library.

const { data, error } = await supabase.from("users").select("*");
if (error) {
  // handle error
}
Copy after login

Graceful Error Handling with Hono RPC

Let us talk about the main star of the show

const onSubmit = async (data: SignUpSchema) => {
  const res = await callRpc(api.auth.signup.$post({ json: data }));

  if (res.error) {
    toast.error(res.error);
    return;
  }

  toast.success("Account created successfully");
  router.navigate({ to: "/" });
};
Copy after login
Copy after login

This function might not look much, but it provides type-safe JSON parameters via RPC. It handles all errors and returns an object containing either data or error, with the data type inferred from the RPC definition based on the endpoint's return type.


Setting up the graceful error handling

Setup Hono Rpc using the official documentation

Setting up the Hono error handler

The backend should always return a text response with the error message and status code.

export const errorHandler = (err: Error | HTTPException, c: Context) => {
  console.log("=== Caught Error ===");
  if (err instanceof HTTPException) {
    return c.text(err.message, err.status);
  }
  if (err instanceof z.ZodError) {
    return c.text(err.errors.map((err) => err.message).join(",\n"), 400);
  }
  console.error(err);
  return c.text("Something went wrong", 500);
};

// Add as a errorHandler on the Hono instance
const app = new Hono();
app.onError(errorHandler);
Copy after login

Based on the Hono's documentation you should throw HTTPException like this

import { HTTPException } from "hono/http-exception";

app.post("/", async (c, next) => {
  if (somethingWentWrong) {
    throw new HTTPException(401, { message: "Custom error message" });
  }
  return c.json({ message: "Success" });
});
Copy after login

Now we know that if there's an error, we will always receive a text response with the error message and status code.


3. Setting up the error handler in the frontend

import { ClientResponse, hc } from "hono/client";
import type { ApiRoutes } from "../../../backend/app";
const client = hc<ApiRoutes>("/");

export const callRpc = async <T>(
  rpc: Promise<ClientResponse<T>>
): Promise<{ data: T; error: null } | { data: null; error: string }> => {
  try {
    const data = await rpc;

    if (!data.ok) {
      const res = await data.text();
      return { data: null, error: res };
    }

    const res = await data.json();
    return { data: res as T, error: null };
  } catch (error) {
    return { data: null, error: (error as Error).message };
  }
};

export default client.api;
Copy after login

callRpc will automatically infer the type of the data based on the RPC definition and return an object containing either data or error.


4. Usage

Everything is typesafe from what you send to what you receive

const onSubmit = async (data: SignUpSchema) => {
  const res = await callRpc(api.auth.signup.$post({ json: data }));

  if (res.error) {
    toast.error(res.error);
    return;
  }

  toast.success("Account created successfully");
  router.navigate({ to: "/" });
};
Copy after login
Copy after login

I have been working in a codebase where it is set up like this and it is the smoothest developer experience I have had. I'm just here to share it.


Drawbacks

  • The backend is limited to returning text for errors and JSON for success responses
  • Doing this pattern shifts away from the idiomatic way of handling errors in javascript
  • You have to handle the error right away, which might not be what you want

The above is the detailed content of Elegant Error Handling and End to End typesafety with Hono RPC. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template