What is the purpose of "throw error" in +server endpoints? #6172
Replies: 5 comments 5 replies
-
import { json } from '@sveltejs/kit';
export const GET: RequestHandler = (req) => {
return json({ error: "Don't send me that junk" }, { status: 422 });
}; |
Beta Was this translation helpful? Give feedback.
-
Really, why throw? Why not make redirect and error a constructor like json? |
Beta Was this translation helpful? Give feedback.
-
I don't have the exact response... But I just changed our OAuth2 auth callback endpoint from In the file, I just renamed the edit: ah and thanks for your svelte content/tips on twitter, nice and useful snippets :) |
Beta Was this translation helpful? Give feedback.
-
I wrote a helper export default async function fetch_json(url, body, method) {
const response = await fetch(url, {
method,
headers: { accept: "application/json" },
body: method === "GET" ? undefined : JSON.stringify(body)
});
if (response.ok) {
return response.json();
} else {
let err = await response.text();
throw err;
}
} Then I wrap the As a side note, I have decided to never use In the case where no information needs to be returned to the client I use |
Beta Was this translation helpful? Give feedback.
-
ok I'm using |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Maybe I'm dense (very likely), but what is the purpose/value of
throw error(...)
in a+server.js
file?Right now, if you
throw error
in an +server endpoint your client, which likely expects JSON in 90% of the cases, will barf on the string response. It took me (an embarrassingly) long time to figure out thatthrow error
was just returning a string and not some structured error object as I was expecting/hoping.You can of course return a
new Response(...)
with error, but that gets clunky real quick.I also tried doing a
throw error(422, JSON.stringify({ error: "..." }))
type response but of course it is just sent astext/plain
notapplication/json
and I don't see a way to change that(?)Is there a planned better way to
throw error
that is an actual convenience method for+server
endpoints or do we need to implement this in userland (hope not 😅). As it stands, it seemsthrow error
on the server is largly useless for most people's use cases (eg. JSON or other type of response beside plain text).Excuse me if this has been posted before, but I did a search of issues/discussions and don't see much on the subject.
Beta Was this translation helpful? Give feedback.
All reactions