diff --git a/docs/content/1.docs/2.guide/2.directory-structure/1.server.md b/docs/content/1.docs/2.guide/2.directory-structure/1.server.md index 9e4c8a8733e..451eb0363dc 100644 --- a/docs/content/1.docs/2.guide/2.directory-structure/1.server.md +++ b/docs/content/1.docs/2.guide/2.directory-structure/1.server.md @@ -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]