docs: add description of returning different status codes (#10059)

This commit is contained in:
Mike Laumann Bellika 2023-01-19 13:08:39 +01:00 committed by GitHub
parent cb607b84ad
commit 49a2dd5d5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -163,6 +163,37 @@ export default defineEventHandler((event) => {
}) })
``` ```
### Error handling
If no errors are thrown, a status code of `200 OK` will be returned. Any uncaught errors will return a `500 Internal Server Error` HTTP Error.
To return other error codes, throw an exception with `createError`
```ts [server/api/validation/[id].ts]
export default defineEventHandler((event) => {
const id = parseInt(event.context.params.id) as number
if (!Number.isInteger(id)) {
throw createError({
statusCode: 400,
statusMessage: 'ID should be an integer',
})
}
return 'All good'
})
```
### Returning other status codes
To return other status codes, you can use the `setResponseStatus` utility.
For example, to return `202 Accepted`
```ts [server/api/validation/[id].ts]
export default defineEventHandler((event) => {
setResponseStatus(event, 202)
})
```
### Accessing Runtime Config ### Accessing Runtime Config
```ts [server/api/foo.ts] ```ts [server/api/foo.ts]