Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

docs: add description of returning different status codes #10059

Merged
merged 7 commits into from
Jan 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/content/1.docs/2.guide/2.directory-structure/1.server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```ts [server/api/foo.ts]
Expand Down