h3-errors
v3.0.0
Published
Assert helpers for h3
Readme
h3-errors
assert and createError helpers for throwing HTTP 4xx and 5xx errors in h3.
Asserts:
// Before:
if (!post) {
throw createError({
statusCode: 404,
message: "Post not found."
})
}
// After:
assertHttp404NotFound(post, "Post not found.")Throws:
// Before:
throw createError({
statusCode: 400,
data: { email: "Invalid e-mail address." },
})
// After:
throw createHttp400BadRequest({ email: "Invalid e-mail address." })Install
npm install h3-errorsUse
In a h3 request handler:
import { assertHttp404NotFound } from "h3-errors"
export default defineEventHandler(async (event) => {
const postId = getRouterParam(event, "postId")!
// post could be undefined.
const post = await db.post
.findOptional(postId)
.select("title", "text")
// Will throw Error 404 if post not found.
assertHttp404NotFound(post, "Post not found.")
// post is typed as not undefined now.
console.log(post.text)
return post
})Error Format
The error value can be:
- string - sets
messagein the JSON response. - object - sets
datain the JSON response. - callback (returning either of the above, for
assertonly) - lazily evaluated if the assertion fails.
Response Structure
{
"statusCode": 400,
"message": "Custom error", // If error was a string
"data": { /* ... */ } // If error was an object
}Examples
// String error
throw createHttp400BadRequest("Invalid input")
// Object error
throw createHttp422UnprocessableEntity({ field: "Email already exists" })
// Callback (assert only)
assertHttp404NotFound(post, () => `Post ${postId} not found`)Exported functions
4xx Client Errors
createHttp400BadRequest/assertHttp400BadRequestcreateHttp401Unauthorized/assertHttp401UnauthorizedcreateHttp402PaymentRequired/assertHttp402PaymentRequiredcreateHttp403Forbidden/assertHttp403ForbiddencreateHttp404NotFound/assertHttp404NotFoundcreateHttp405MethodNotAllowed/assertHttp405MethodNotAllowedcreateHttp406NotAcceptable/assertHttp406NotAcceptablecreateHttp407ProxyAuthenticationRequired/assertHttp407ProxyAuthenticationRequiredcreateHttp409Conflict/assertHttp409ConflictcreateHttp410Gone/assertHttp410GonecreateHttp411LengthRequired/assertHttp411LengthRequiredcreateHttp412PreconditionFailed/assertHttp412PreconditionFailedcreateHttp413PayloadTooLarge/assertHttp413PayloadTooLargecreateHttp415UnsupportedMediaType/assertHttp415UnsupportedMediaTypecreateHttp422UnprocessableEntity/assertHttp422UnprocessableEntitycreateHttp429TooManyRequests/assertHttp429TooManyRequests
5xx Server Errors
createHttp500InternalServerError/assertHttp500InternalServerErrorcreateHttp501NotImplemented/assertHttp501NotImplementedcreateHttp502BadGateway/assertHttp502BadGatewaycreateHttp503ServiceUnavailable/assertHttp503ServiceUnavailablecreateHttp504GatewayTimeout/assertHttp504GatewayTimeout
Generic
createHttpError/assertHttpError- create or assert with arbitrary status codecreateCreateHttpError/createAssertHttpError- create shortcut function for arbitrary HTTP codes
