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); } }
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 }
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 }
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: "/" }); };
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);
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" }); });
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;
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: "/" }); };
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
