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
Top comments (1)
dev.to/hanzla-baig/top-90-resource...