Handling errors
In Sequoia there is a great mechanism that lets you handle the errors the way you like.
Also there is a whole lot of error classes that correspond to HTTP error statuses like BadRequestError
, UnauthorizedError
and others. You can throw them in your middleware just like this:
import { Application, HTTPStatus, Router, NotAllowedError, HTTPResponse } from 'jsr:@sequoia/sequoia'
const app = new Application()
const router = new Router()
router.GET('/secure-resource', (context) => {
const headers = context.response.headers
const token = headers.get('Authorization')
if (!token) {
throw new NotAllowedError(
'You are not allowed to access this resource as of right now',
)
}
// Will result in the same output as the block above
// if (!token) {
// return new HTTPResponse({
// status: HTTPStatus.NOT_ALLOWED,
// body: 'You are not allowed to access this resource as of right now'
// })
// }
})
app.useRouter(router)
await app.listen({ port: 8000 })
Sequoia will take care of this thrown error and will render an HTTPResponse
with status of 405: Not Allowed
. No need to construct it, the library will do this for you.
To define a custom error handler, set it in your app:
import { Application, Context, HTTPError, HTTPResponse } from 'jsr:@sequoia/sequoia'
const app = new Application()
const errorHandler = (context: Context, error: HTTPError): HTTPResponse => {
return new HTTPResponse({
status: error.code,
body: 'Oops, an error occurred!'
})
}
app.handleErrors(errorHandler)
await app.listen({ port: 8000 })
This function will now be ran whenever an exception of HTTPError
class will be thrown anywhere in a middleware. The response that's returned from this error handler will be rendered to the user