https://a.storyblok.com/f/283157/1920x800/18e18690e6/detailed_error.jpg

Web error handling concept

Published: Oct 6, 2024
• • •

Handling errors in the frontend

In the frontend, you just have to fetch the response, check the status code and, when it is an error, display a toast with the error code.

Let's make things simple by defining the error codes in a simple object:

const errorCodes = {
	"ERROR_INTERNAL_SERVER_ERROR": "Oops, something went wrong...",
	"ERROR_INPUT_EMPTY": "Your input was empty, please enter something",
	"ERROR_INPUT_EMAIL_INVALID": "The email you've entered is not valid",
	...
};

Now let's make a request and then check the error code. Let's say we have a function "showToast" for simply displaying error toasts:

function isError(response): boolean {
	if (!response.ok) {
		const data = await response.json();
		const {errorCode, error} = data;
		// Get the error message from the object or use
		// "error" from the response as fallback
		const errorMessage = errorCodes[errorCode] ?? error;
		showToast(errorMessage);
		return false;
	}
	
	return true;
}

async function doSomething() {
	const response = await fetch("/api"); // Your api call
	if (isError(response)) {
		return;
	}
	
	// Do something with the response
}

That's it! You can use the function "isError" every time you make an API request to your backend, check if it's okay, and it will automatically display the toast with the correct error message to the user.

You only have to implement the "success case" and maintain the object containing the error messages. In production, you may want to use an i18n library to manage the error messages in different languages or use a different way to manage your error codes and error messages. Feel free to play around and find out what works best for your scenario.