SaveError Class for SvelteKit Superforms

March 23, 2024 Updated: April 17, 2024

SaveError Class for SvelteKit Superforms

Table of Contents

The Code

The following code is a class that can be used to streamline error handling with Superforms. It is designed to be used with the SaveResult type, which is a promise that resolves to either the saved object or a SaveError object. The SaveError object can be used to provide a more detailed error message to the user, including the field that caused the error and the HTTP status code.

The static from method can be used to handle other types of errors that occur during the save process and convert them to SaveError objects.

The toForm method can be returned from the form action to display the error message to the user.

Using SaveResult and SaveError

The following code demonstrates how to use the SaveResult type and the SaveError class in a function that saves a log entry for a character. The function returns an object that matches the defined return type in SaveResult (the first type argument) or a SaveError object with the defined schema (the second type argument).

Returning the Error to Superforms

The following code demonstrates how to use the SaveError class in a form action. The saveLog action saves a log entry for a character. If the save is successful, the user is redirected to the character page. If there is an error, the SaveError object’s toForm method is called to return the error message to the user.

Using Without Superforms

You can also use the SaveError class to handle errors in forms that do not use Superforms. The following code demonstrates how to use the SaveError class in a form action that deletes a dungeon master. If an error occurs, SvelteKit’s fail function is called to return the error message to the form.