N
Nuxtβ€’2mo ago
Stefan

Typescript types for server errors

For API requests I wrote a little script to fetch data from a server. It works, but for statusCode and statusMessage my editor is yelling at me that the property does not exist on type 'Error'. I get the feeling that I need a special type for server errors, because similar code is no problem on e.g. components, but I can't figure out what I need to do to make my editor happy. It would be great if someone could point me in the right direction to figure this out. Thanks in advance! Here is my code:
import type { EventHandlerRequest, H3Event } from 'h3';

export async function apiRequest(event: H3Event<EventHandlerRequest>, path: string) {
const body = await readBody(event);
const { apiUrl, apiKey } = useRuntimeConfig();

try {
return await $fetch(`${apiUrl}/${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
query: { 'api-key': apiKey },
body,
});
} catch (error: unknown) {
if (error instanceof Error) {
throw createError({
...error,
statusCode: error.statusCode,
statusMessage: error.statusMessage,
})
}
}
}
import type { EventHandlerRequest, H3Event } from 'h3';

export async function apiRequest(event: H3Event<EventHandlerRequest>, path: string) {
const body = await readBody(event);
const { apiUrl, apiKey } = useRuntimeConfig();

try {
return await $fetch(`${apiUrl}/${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
query: { 'api-key': apiKey },
body,
});
} catch (error: unknown) {
if (error instanceof Error) {
throw createError({
...error,
statusCode: error.statusCode,
statusMessage: error.statusMessage,
})
}
}
}
2 Replies
xergic
xergicβ€’2mo ago
You should use FetchError (from ofetch) instead of Error when checking instanceof.
Stefan
Stefanβ€’2mo ago
This seems to be working. Thank you πŸ™