From 49a2dd5d5a43b50aca8334cf10c1700a8327d83f Mon Sep 17 00:00:00 2001 From: Mike Laumann Bellika <5175031+MikeBellika@users.noreply.github.com> Date: Thu, 19 Jan 2023 13:08:39 +0100 Subject: [PATCH] docs: add description of returning different status codes (#10059) --- .../2.guide/2.directory-structure/1.server.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) 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 9e4c8a8733..451eb0363d 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]