Stefan
Stefan
NNuxt
Created by Stefan on 7/1/2024 in #❓・help
Response Body in Error with useFetch
No description
3 replies
NNuxt
Created by Stefan on 6/21/2024 in #❓・help
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,
})
}
}
}
3 replies