Skip to main content

Erreurs

Les erreurs sont une réalité inévitable du développement logiciel. SvelteKit gère les erreurs de manière différente selon l’endroit où elles se produisent, leur type, et la nature de la requête entrante.

Objets d’erreurs

SvelteKit distingue les erreurs prévues et imprévues, les deux typologies étant représentées en tant que simple objets { message: string } par défaut.

Vous pouvez ajouter des propriétés additionnelles, comme code ou un id de suivi, comme montré dans les exemples ci-dessous. (Lorsque vous utilisez TypeScript ceci requiert que vous redéfinissiez le type Error comme décrit dans la section sur typage).

Erreurs prévues

Une erreur prévue est une erreur créée avec l’utilitaire error importé depuis @sveltejs/kit :

src/routes/blog/[slug]/+page.server
import { function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
import * as module "$lib/server/database"db from '$lib/server/database'; /** @type {import('./$types').PageServerLoad} */ export async function function load(event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
@type{import('./$types').PageServerLoad}
load
({ params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
}) {
const
const post: {
    title: string;
    content: string;
} | undefined
post
= await module "$lib/server/database"db.
function getPost(slug: string): Promise<{
    title: string;
    content: string;
} | undefined>
getPost
(params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
.slug);
if (!
const post: {
    title: string;
    content: string;
} | undefined
post
) {
function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Introuvable' }); } return {
post: {
    title: string;
    content: string;
}
post
};
}
import { function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
import * as module "$lib/server/database"db from '$lib/server/database'; import type { type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>PageServerLoad } from './$types'; export const const load: PageServerLoadload: type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>PageServerLoad = async ({ params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
}) => {
const
const post: {
    title: string;
    content: string;
} | undefined
post
= await module "$lib/server/database"db.
function getPost(slug: string): Promise<{
    title: string;
    content: string;
} | undefined>
getPost
(params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
.slug);
if (!
const post: {
    title: string;
    content: string;
} | undefined
post
) {
function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Introuvable' }); } return {
post: {
    title: string;
    content: string;
}
post
};
};

Ceci lève une exception que SvelteKit attrape, lui permettant de définir le statut de la réponse à 404 et de rendre le composant +error.svelte approprié, dans lequel page.error est l’objet fourni en tant que second argument à error(...).

src/routes/+error
<script>
	import { page } from '$app/state';
</script>

<h1>{page.error.message}</h1>
<script lang="ts">
	import { page } from '$app/state';
</script>

<h1>{page.error.message}</h1>
Legacy mode

$app/state a été ajouté dans la version 2.12 de SvelteKit. Si vous utilisez une version plus récente ou si vous utilisez Svelte 4, veuillez plutôt utiliser $app/stores.

Vous pouvez ajouter des propriétés additionnelles à l’objet d’erreur si besoin...

function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Introuvable', App.Error.code: stringcode: 'NOT_FOUND' });

... ou bien fournir une chaîne de caractères en tant que deuxième argument, pour plus de simplicité :

error(404, { message: 'Introuvable' });
function error(status: number, body?: {
    message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(404, 'Introuvable');

Dans SvelteKit 1.x vous deviez lever une error vous-même avec throw.

Erreurs imprévues

Une erreur imprévue est toute autre exception se produisant pendant le traitement d’une requête. Puisque celles-ci peuvent contenir des informations sensibles, les messages d’erreur et stacktraces ne sont pas exposées aux utilisateurs et utilisatrices.

Par défaut, les erreurs imprévues sont affichées dans la console, (ou, en production, dans vos logs de serveur), tandis que l’erreur exposée aux utilisateurs et utilisatrices reste générique :

{ "message": "Internal Error" }

Les erreurs inattendues vont être passées au hook handleError, où vous pouvez ajouter votre propre gestion d’erreur — par exemple, envoyer ces erreurs à un service de suivi d’erreur, ou renvoyer un objet d’erreur personnalisé qui va devenir $page.error.

Réponses

Si une erreur se produit au sein de la fonction handle ou d’un gestionnaire de requête +server.js, SvelteKit va répondre avec soit une page d’erreur de secours, soit une représentation JSON de l’objet d’erreur, en fonction des en-têtes de requête Accept.

Vous pouvez personnaliser la page d’erreur de secours en ajoutant un fichier src/error.html :

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>%sveltekit.error.message%</title>
	</head>
	<body>
		<h1>Ma page d'erreur personnalisée</h1>
		<p>Statut : %sveltekit.status%</p>
		<p>Message : %sveltekit.error.message%</p>
	</body>
</html>

SvelteKit va remplacer %sveltekit.status% et %sveltekit.error.message% avec leurs valeurs respectives.

Si l’erreur se produit plutôt au sein d’une fonction load lors du rendu d’une page, SvelteKit va rendre le composant +error.svelte le plus proche de là où l’erreur s’est produite. Si l’erreur se produit au sein d’une fonction load d’un fichier +layout(.server).js, la frontière d’erreur la plus proche est un fichier +error.svelte au-dessus de ce layout (et non à côté).

Il y a une exception lorsque l’erreur se produit au sein du fichier +layout.js ou +layout.server.js racine, puisque le layout racine devrait normalement contenir le composant +error.svelte. Dans ce cas, SvelteKit va utiliser la page d’erreur de secours.

Typage

Si vous utilisez TypeScript et avez besoin de personnaliser la forme des erreurs, vous pouvez le faire en déclarant une interface App.Error dans votre application (par convention, dans le fichier src/app.d.ts, bien qu’il puisse se trouver dans n’importe dossier dont TypeScript a connaissance) :

src/app.d
declare global {
	namespace App {
		interface interface App.Error

Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.

Error
{
App.Error.code: stringcode: string; App.Error.id: stringid: string; } } } export {};

Cette interface va toujours inclure une propriété message: string.

Plus de lecture

Modifier cette page sur Github llms.txt

précédent suivant