[✨] Throw server$ errors with a specific status code
Closed this issue · 4 comments
DustinJSilk commented
Is your feature request related to a problem?
Currently all server$
errors return an HTTP 500 error which can't be configured per request.
Describe the solution you'd like
I'd like to be able to throw a custom error which includes a status code.
Option A:
import { ServerError } from `@builder.io/qwik-city`
const myFunc = server$(() => {
throw new ServerError(404, { /** Some response data */ })
})
Option B:
const myFunc = server$(() => {
throw this.error(404, { /** Some response data */ })
})
Describe alternatives you've considered
Currently the choices are:
- Return 200 with a union type for both a successful and unsuccessful response
- Throw an error that is always a 500
Additional context
No response
wmertens commented
I like it and prefer option A
PatrickJS commented
ok I have it here. but you have to make sure you know how to detect the error from the response object json
#6290
this will only work for any status that fails res.ok and not 500 status
const myFunc = server$(() => {
if (throwing) {
throw new ServerError(404, { error: true, data: {} })
}
return { error: false, data: {}}
})
const data = await myFunc()
if (data.error) {
console.log(data.error)
}
this pattern should be way better
const myFunc = server$(() => {
if (throwing) {
const errorData = {};
throw new ServerError(404, [ errorData ])
}
const data = {};
return [null, data]
})
const [err, data] = await myFunc()
if (err) {
console.log(err)
}
DustinJSilk commented
Amazing, thank you @PatrickJS !
PatrickJS commented
you have to import from import { ServerError } from "@builder.io/qwik-city/middleware/request-handler";
in the next release