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

Commit

Permalink
docs: add description of returning different status codes (#10059)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeBellika authored Jan 19, 2023
1 parent cb607b8 commit 49a2dd5
Showing 1 changed file with 31 additions and 0 deletions.
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

0 comments on commit 49a2dd5

Please sign in to comment.