Hooks
「Hooks」是您宣告的全應用程式函數,SvelteKit 將在響應特定事件時呼叫這些函數,讓您可以精細地控制框架的行為。
有三個 Hooks 檔案,都是可選的
src/hooks.server.js
— 您的應用程式的伺服器 Hookssrc/hooks.client.js
— 您的應用程式的客戶端 Hookssrc/hooks.js
— 您的應用程式在客戶端和伺服器上運行的 Hooks
這些模組中的程式碼將在應用程式啟動時運行,使其可用於初始化資料庫客戶端等等。
您可以使用
config.kit.files.hooks
配置這些檔案的位置。
伺服器 Hooks
以下 Hooks 可以添加到 src/hooks.server.js
handle
此函數在 SvelteKit 伺服器每次收到 請求 時執行 — 無論是在應用程式運行時還是 預先渲染 期間 — 並決定 回應。它接收一個代表請求的 event
物件和一個稱為 resolve
的函數,該函數會渲染路由並產生一個 Response
。這允許您修改回應標頭或主體,或完全繞過 SvelteKit(例如,用於以程式方式實作路由)。
/** @type {import('@sveltejs/kit').Handle} */
export async function function handle({ event, resolve }: {
event: any;
resolve: any;
}): Promise<any>
handle({ event: any
event, resolve: any
resolve }) {
if (event: any
event.url.pathname.startsWith('/custom')) {
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
This Fetch API interface represents the response to a request.
Response('custom response');
}
const const response: any
response = await resolve: any
resolve(event: any
event);
return const response: any
response;
}
import type { type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle } from '@sveltejs/kit';
export const const handle: Handle
handle: type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle = async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>
event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve }) => {
if (event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.url: URL
The requested URL.
url.URL.pathname: string
pathname.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith('/custom')) {
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
This Fetch API interface represents the response to a request.
Response('custom response');
}
const const response: Response
response = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>
event);
return const response: Response
response;
};
靜態資產(包括已經預先渲染的頁面)的請求 不 由 SvelteKit 處理。
如果未實作,則預設為 ({ event, resolve }) => resolve(event)
。
locals
要將自訂資料添加到請求中,該資料會傳遞給 +server.js
中的處理程式和伺服器 load
函數,請填寫 event.locals
物件,如下所示。
/** @type {import('@sveltejs/kit').Handle} */
export async function function handle(input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<...>
handle({ event: RequestEvent<Partial<Record<string, string>>, string | null>
event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve }) {
event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.locals: App.Locals
Contains custom data that was added to the request within the server handle hook
.
locals.App.Locals.user: User
user = await const getUserInformation: (cookie: string | void) => Promise<User>
getUserInformation(event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.cookies: Cookies
Get or set cookies related to the current request
cookies.Cookies.get(name: string, opts?: CookieParseOptions): string | undefined
Gets a cookie that was previously set with cookies.set
, or from the request headers.
get('sessionid'));
const const response: Response
response = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>
event);
const response: Response
response.Response.headers: Headers
headers.Headers.set(name: string, value: string): void
set('x-custom-header', 'potato');
return const response: Response
response;
}
import type { type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle } from '@sveltejs/kit';
export const const handle: Handle
handle: type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle = async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>
event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve }) => {
event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.locals: App.Locals
Contains custom data that was added to the request within the server handle hook
.
locals.App.Locals.user: User
user = await const getUserInformation: (cookie: string | void) => Promise<User>
getUserInformation(event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.cookies: Cookies
Get or set cookies related to the current request
cookies.Cookies.get(name: string, opts?: CookieParseOptions): string | undefined
Gets a cookie that was previously set with cookies.set
, or from the request headers.
get('sessionid'));
const const response: Response
response = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>
event);
const response: Response
response.Response.headers: Headers
headers.Headers.set(name: string, value: string): void
set('x-custom-header', 'potato');
return const response: Response
response;
};
您可以定義多個 handle
函數,並使用 sequence
輔助函數執行它們。
resolve
也支援第二個可選參數,讓您可以更精細地控制回應的渲染方式。該參數是一個物件,可以具有以下欄位
transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined>
— 將自訂轉換套用於 HTML。如果done
為 true,則它是最後一個區塊。不保證區塊是格式良好的 HTML(例如,它們可能包含元素的開始標籤,但不包含其結束標籤),但它們始終會以合理的邊界分割,例如%sveltekit.head%
或版面配置/頁面元件。filterSerializedResponseHeaders(name: string, value: string): boolean
— 決定當load
函數使用fetch
載入資源時,應包含在序列化回應中的標頭。預設情況下,不會包含任何標頭。preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean
— 決定應將哪些檔案添加到<head>
標籤中以進行預載。該方法會以在建置時找到的每個檔案呼叫,同時建構程式碼區塊 — 因此,如果您例如在+page.svelte
中有import './styles.css
,則在造訪該頁面時,將會使用該 CSS 檔案的解析路徑呼叫preload
。請注意,在開發模式下,不 會呼叫preload
,因為它取決於在建置時發生的分析。預載可以透過更早下載資產來提高效能,但如果過多不必要的下載,也可能會造成損害。預設情況下,將會預載js
和css
檔案。目前完全不會預載asset
檔案,但我們可能會在評估回饋後再添加此功能。
/** @type {import('@sveltejs/kit').Handle} */
export async function function handle({ event, resolve }: {
event: any;
resolve: any;
}): Promise<any>
handle({ event: any
event, resolve: any
resolve }) {
const const response: any
response = await resolve: any
resolve(event: any
event, {
transformPageChunk: ({ html }: {
html: any;
}) => any
transformPageChunk: ({ html: any
html }) => html: any
html.replace('old', 'new'),
filterSerializedResponseHeaders: (name: any) => any
filterSerializedResponseHeaders: (name: any
name) => name: any
name.startsWith('x-'),
preload: ({ type, path }: {
type: any;
path: any;
}) => any
preload: ({ type: any
type, path: any
path }) => type: any
type === 'js' || path: any
path.includes('/important/')
});
return const response: any
response;
}
import type { type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle } from '@sveltejs/kit';
export const const handle: Handle
handle: type Handle = (input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>
The handle
hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event
object representing the request and a function called resolve
, which renders the route and generates a Response
.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Handle = async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>
event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve }) => {
const const response: Response
response = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>
event, {
ResolveOptions.transformPageChunk?(input: {
html: string;
done: boolean;
}): MaybePromise<string | undefined>
Applies custom transforms to HTML. If done
is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element’s opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as %sveltekit.head%
or layout/page components.
transformPageChunk: ({ html: string
html }) => html: string
html.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)
Replaces text in a string, using a regular expression or search string.
replace('old', 'new'),
ResolveOptions.filterSerializedResponseHeaders?(name: string, value: string): boolean
Determines which headers should be included in serialized responses when a load
function loads a resource with fetch
.
By default, none will be included.
filterSerializedResponseHeaders: (name: string
name) => name: string
name.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith('x-'),
ResolveOptions.preload?(input: {
type: "font" | "css" | "js" | "asset";
path: string;
}): boolean
Determines what should be added to the <head>
tag to preload it.
By default, js
and css
files will be preloaded.
preload: ({ type: "font" | "css" | "js" | "asset"
type, path: string
path }) => type: "font" | "css" | "js" | "asset"
type === 'js' || path: string
path.String.includes(searchString: string, position?: number): boolean
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
includes('/important/')
});
return const response: Response
response;
};
請注意,resolve(...)
永遠不會擲回錯誤,它將始終以適當的狀態碼傳回 Promise<Response>
。如果 handle
期間在其他地方擲回錯誤,則會將其視為致命錯誤,SvelteKit 將會根據 Accept
標頭,以錯誤的 JSON 表示形式或備用錯誤頁面(可透過 src/error.html
自訂)進行回應。您可以在 這裡閱讀更多關於錯誤處理的資訊。
handleFetch
此函數允許您修改(或替換)在伺服器(或在預先渲染期間)運行的 load
或 action
函數內部發生的 fetch
請求。
例如,當使用者執行客戶端導覽到對應頁面時,您的 load
函數可能會向公用 URL(例如 https://api.yourapp.com
)發出請求,但在 SSR 期間,直接點擊 API 可能更有意義(繞過其與公共網際網路之間的所有 Proxy 和負載平衡器)。
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function function handleFetch({ request, fetch }: {
request: any;
fetch: any;
}): Promise<any>
handleFetch({ request: any
request, fetch: any
fetch }) {
if (request: any
request.url.startsWith('https://api.yourapp.com/')) {
// clone the original request, but change the URL
request: any
request = new var Request: new (input: RequestInfo | URL, init?: RequestInit) => Request
This Fetch API interface represents a resource request.
Request(
request: any
request.url.replace('https://api.yourapp.com/', 'https://127.0.0.1:9999/'),
request: any
request
);
}
return fetch: any
fetch(request: any
request);
}
import type { type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>
The handleFetch
hook allows you to modify (or replace) a fetch
request that happens inside a load
function that runs on the server (or during pre-rendering)
HandleFetch } from '@sveltejs/kit';
export const const handleFetch: HandleFetch
handleFetch: type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>
The handleFetch
hook allows you to modify (or replace) a fetch
request that happens inside a load
function that runs on the server (or during pre-rendering)
HandleFetch = async ({ request: Request
request, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch }) => {
if (request: Request
request.Request.url: string
Returns the URL of request as a string.
url.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith('https://api.yourapp.com/')) {
// clone the original request, but change the URL
request: Request
request = new var Request: new (input: RequestInfo | URL, init?: RequestInit) => Request
This Fetch API interface represents a resource request.
Request(
request: Request
request.Request.url: string
Returns the URL of request as a string.
url.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)
Replaces text in a string, using a regular expression or search string.
replace('https://api.yourapp.com/', 'https://127.0.0.1:9999/'),
request: Request
request
);
}
return fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response> (+1 overload)
fetch(request: Request
request);
};
憑證
對於同源請求,SvelteKit 的 fetch
實作將會轉發 cookie
和 authorization
標頭,除非 credentials
選項設定為 "omit"
。
對於跨域請求,如果請求 URL 屬於應用程式的子網域,則會包含 cookie
— 例如,如果您的應用程式位於 my-domain.com
上,而您的 API 位於 api.my-domain.com
上,則請求中將包含 Cookie。
如果您的應用程式和 API 位於同級子網域上 — 例如 www.my-domain.com
和 api.my-domain.com
— 則屬於通用父網域(例如 my-domain.com
)的 Cookie 將 不 會被包含,因為 SvelteKit 無法知道 Cookie 所屬的網域。在這些情況下,您需要使用 handleFetch
手動包含 Cookie
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function function handleFetch({ event, request, fetch }: {
event: any;
request: any;
fetch: any;
}): Promise<any>
handleFetch({ event: any
event, request: any
request, fetch: any
fetch }) {
if (request: any
request.url.startsWith('https://api.my-domain.com/')) {
request: any
request.headers.set('cookie', event: any
event.request.headers.get('cookie'));
}
return fetch: any
fetch(request: any
request);
}
import type { type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>
The handleFetch
hook allows you to modify (or replace) a fetch
request that happens inside a load
function that runs on the server (or during pre-rendering)
HandleFetch } from '@sveltejs/kit';
export const const handleFetch: HandleFetch
handleFetch: type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>
The handleFetch
hook allows you to modify (or replace) a fetch
request that happens inside a load
function that runs on the server (or during pre-rendering)
HandleFetch = async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>
event, request: Request
request, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch }) => {
if (request: Request
request.Request.url: string
Returns the URL of request as a string.
url.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith('https://api.my-domain.com/')) {
request: Request
request.Request.headers: Headers
Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers.Headers.set(name: string, value: string): void
set('cookie', event: RequestEvent<Partial<Record<string, string>>, string | null>
event.RequestEvent<Partial<Record<string, string>>, string | null>.request: Request
The original request object
request.Request.headers: Headers
Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers.Headers.get(name: string): string | null
get('cookie'));
}
return fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response> (+1 overload)
fetch(request: Request
request);
};
共用 Hooks
以下內容可以添加到 src/hooks.server.js
和 src/hooks.client.js
handleError
如果在載入或渲染期間擲回非預期錯誤,則會使用 error
、event
、status
程式碼和 message
呼叫此函數。這允許執行兩件事
- 您可以記錄錯誤
- 您可以產生對使用者安全的錯誤自訂表示,省略敏感詳細資料,例如訊息和堆疊追蹤。傳回值(預設為
{ message }
)會變成$page.error
的值。
對於從您的程式碼(或您的程式碼呼叫的程式庫程式碼)擲回的錯誤,狀態碼將為 500,訊息將為「內部錯誤」。雖然 error.message
可能包含不應向使用者公開的敏感資訊,但 message
是安全的(儘管對一般使用者而言沒有意義)。
若要以類型安全的方式將更多資訊添加到 $page.error
物件中,您可以透過宣告 App.Error
介面(必須包含 message: string
,以保證合理的備用行為)來自訂預期的形狀。這允許您例如附加一個追蹤 ID,供使用者在與您的技術支援人員通信時引用
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.message: string
message: string;
App.Error.errorId: string
errorId: string;
}
}
}
export {};
import * as module "@sentry/sveltekit"
Sentry from '@sentry/sveltekit';
module "@sentry/sveltekit"
Sentry.const init: (opts: any) => void
init({/*...*/})
/** @type {import('@sveltejs/kit').HandleServerError} */
export async function function handleError(input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}): MaybePromise<void | App.Error>
handleError({ error: unknown
error, event: RequestEvent<Partial<Record<string, string>>, string | null>
event, status: number
status, message: string
message }) {
const const errorId: `${string}-${string}-${string}-${string}-${string}`
errorId = var crypto: Crypto
crypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
Available only in secure contexts.
randomUUID();
// example integration with https://sentry.io/
module "@sentry/sveltekit"
Sentry.const captureException: (error: any, opts: any) => void
captureException(error: unknown
error, {
extra: {
event: RequestEvent<Partial<Record<string, string>>, string | null>;
errorId: `${string}-${string}-${string}-${string}-${string}`;
status: number;
}
extra: { event: RequestEvent<Partial<Record<string, string>>, string | null>
event, errorId: `${string}-${string}-${string}-${string}-${string}`
errorId, status: number
status }
});
return {
App.Error.message: string
message: 'Whoops!',
errorId: `${string}-${string}-${string}-${string}-${string}`
errorId
};
}
import * as module "@sentry/sveltekit"
Sentry from '@sentry/sveltekit';
import type { type HandleServerError = (input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>
The server-side handleError
hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.
Make sure that this function never throws an error.
HandleServerError } from '@sveltejs/kit';
module "@sentry/sveltekit"
Sentry.const init: (opts: any) => void
init({/*...*/})
export const const handleError: HandleServerError
handleError: type HandleServerError = (input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>
The server-side handleError
hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.
Make sure that this function never throws an error.
HandleServerError = async ({ error: unknown
error, event: RequestEvent<Partial<Record<string, string>>, string | null>
event, status: number
status, message: string
message }) => {
const const errorId: `${string}-${string}-${string}-${string}-${string}`
errorId = var crypto: Crypto
crypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
Available only in secure contexts.
randomUUID();
// example integration with https://sentry.io/
module "@sentry/sveltekit"
Sentry.const captureException: (error: any, opts: any) => void
captureException(error: unknown
error, {
extra: {
event: RequestEvent<Partial<Record<string, string>>, string | null>;
errorId: `${string}-${string}-${string}-${string}-${string}`;
status: number;
}
extra: { event: RequestEvent<Partial<Record<string, string>>, string | null>
event, errorId: `${string}-${string}-${string}-${string}-${string}`
errorId, status: number
status }
});
return {
App.Error.message: string
message: 'Whoops!',
errorId: `${string}-${string}-${string}-${string}-${string}`
errorId
};
};
import * as module "@sentry/sveltekit"
Sentry from '@sentry/sveltekit';
module "@sentry/sveltekit"
Sentry.const init: (opts: any) => void
init({/*...*/})
/** @type {import('@sveltejs/kit').HandleClientError} */
export async function function handleError(input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}): MaybePromise<void | App.Error>
handleError({ error: unknown
error, event: NavigationEvent<Partial<Record<string, string>>, string | null>
event, status: number
status, message: string
message }) {
const const errorId: `${string}-${string}-${string}-${string}-${string}`
errorId = var crypto: Crypto
crypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
Available only in secure contexts.
randomUUID();
// example integration with https://sentry.io/
module "@sentry/sveltekit"
Sentry.const captureException: (error: any, opts: any) => void
captureException(error: unknown
error, {
extra: {
event: NavigationEvent<Partial<Record<string, string>>, string | null>;
errorId: `${string}-${string}-${string}-${string}-${string}`;
status: number;
}
extra: { event: NavigationEvent<Partial<Record<string, string>>, string | null>
event, errorId: `${string}-${string}-${string}-${string}-${string}`
errorId, status: number
status }
});
return {
App.Error.message: string
message: 'Whoops!',
errorId: `${string}-${string}-${string}-${string}-${string}`
errorId
};
}
import * as module "@sentry/sveltekit"
Sentry from '@sentry/sveltekit';
import type { type HandleClientError = (input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>
The client-side handleError
hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.
Make sure that this function never throws an error.
HandleClientError } from '@sveltejs/kit';
module "@sentry/sveltekit"
Sentry.const init: (opts: any) => void
init({/*...*/})
export const const handleError: HandleClientError
handleError: type HandleClientError = (input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>
The client-side handleError
hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.
Make sure that this function never throws an error.
HandleClientError = async ({ error: unknown
error, event: NavigationEvent<Partial<Record<string, string>>, string | null>
event, status: number
status, message: string
message }) => {
const const errorId: `${string}-${string}-${string}-${string}-${string}`
errorId = var crypto: Crypto
crypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
Available only in secure contexts.
randomUUID();
// example integration with https://sentry.io/
module "@sentry/sveltekit"
Sentry.const captureException: (error: any, opts: any) => void
captureException(error: unknown
error, {
extra: {
event: NavigationEvent<Partial<Record<string, string>>, string | null>;
errorId: `${string}-${string}-${string}-${string}-${string}`;
status: number;
}
extra: { event: NavigationEvent<Partial<Record<string, string>>, string | null>
event, errorId: `${string}-${string}-${string}-${string}-${string}`
errorId, status: number
status }
});
return {
App.Error.message: string
message: 'Whoops!',
errorId: `${string}-${string}-${string}-${string}-${string}`
errorId
};
};
在
src/hooks.client.js
中,handleError
的類型為HandleClientError
,而不是HandleServerError
,且event
是NavigationEvent
而不是RequestEvent
。
對於 預期 的錯誤(使用從 @sveltejs/kit
匯入的 error
函數擲回的錯誤),不會呼叫此函數。
在開發期間,如果因 Svelte 程式碼中的語法錯誤而發生錯誤,則傳入的錯誤會附加一個 frame
屬性,以突出顯示錯誤的位置。
請確保
handleError
永遠 不會擲回錯誤
通用 Hooks
以下內容可以添加到 src/hooks.js
。通用 Hooks 在伺服器和客戶端上運行(不要與特定於環境的共用 Hooks 混淆)。
reroute
此函數在 handle
之前運行,讓您可以變更 URL 轉換為路由的方式。傳回的路徑名稱(預設為 url.pathname
)用於選取路由及其參數。
例如,您可能有一個 src/routes/[[lang]]/about/+page.svelte
頁面,該頁面應可作為 /en/about
或 /de/ueber-uns
或 /fr/a-propos
存取。您可以使用 reroute
來實作此功能
/** @type {Record<string, string>} */
const const translated: {
'/en/about': string;
'/de/ueber-uns': string;
'/fr/a-propos': string;
}
translated = {
'/en/about': '/en/about',
'/de/ueber-uns': '/de/about',
'/fr/a-propos': '/fr/about',
};
/** @type {import('@sveltejs/kit').Reroute} */
export function function reroute({ url }: {
url: any;
}): any
reroute({ url: any
url }) {
if (url: any
url.pathname in const translated: {
'/en/about': string;
'/de/ueber-uns': string;
'/fr/a-propos': string;
}
translated) {
return const translated: {
'/en/about': string;
'/de/ueber-uns': string;
'/fr/a-propos': string;
}
translated[url: any
url.pathname];
}
}
import type { type Reroute = (event: {
url: URL;
}) => void | string
The reroute
hook allows you to modify the URL before it is used to determine which route to render.
Reroute } from '@sveltejs/kit';
const const translated: Record<string, string>
translated: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record<string, string> = {
'/en/about': '/en/about',
'/de/ueber-uns': '/de/about',
'/fr/a-propos': '/fr/about',
};
export const const reroute: Reroute
reroute: type Reroute = (event: {
url: URL;
}) => void | string
The reroute
hook allows you to modify the URL before it is used to determine which route to render.
Reroute = ({ url: URL
url }) => {
if (url: URL
url.URL.pathname: string
pathname in const translated: Record<string, string>
translated) {
return const translated: Record<string, string>
translated[url: URL
url.URL.pathname: string
pathname];
}
};
lang
參數將會正確地從傳回的路徑名稱中衍生。
使用 reroute
將 不會 變更瀏覽器網址列的內容或 event.url
的值。