Error Handling 🚨
We know how complicating error handling can be, which is why we've taking the time to make this process seemlessly easy for you to work with.
Veloz kits comes with built-in error handlers done the right way for you hackers.
The codebase contain some reusable utilities functions which tend to make this process a lot easier for you to work with.
Server Side Error Handling ☁️
Next.js App Router (API Routes)
We've taken the time to create a custom error handler for you to work with, be it VALIDATION_ERROR
, CUSTOM_ERROR
..etc let take a look at some of them.
Custom Error
A custom error class that extends the default Error class called HttpException
, this is used to throw custom errors in your codebase and can be found in the /src/app/api/utils/exception.(ts)
file.
The code is self-explanatory, we're just extending the default Error class and adding some extra properties to it, which we'll be using later on. Whenever there's a need to throw an error to the client from the server, you simply invoke the class and pass in the required parameters.
_10throw new HttpException(_10 RESPONSE_CODE.USER_ALREADY_EXIST, // error code (meant for debugging purpose)_10 "User already exist", // message_10 400 // status code_10);
You would notice the code
property which is of type RESPONSE_CODE
, this is an enum that contains all the possible error codes that can be thrown from the server, you can find it in the /src/app/api/types/index.ts
file.
But, How then does the error get handled? well, good question my friend.
A custom error handler middleware called CatchError()
is used to handle all errors thrown from the server, this middleware can be found in the src/app/api/utils/_error.(ts)
file. Notice the underscore before the error
name, this is to prevent an override to default next.js custom error
file.
This error handler is as simple as your Grade 8 math 😅. It an HOF
which takes in a function, wraps the function in a try...catch
block and returns the function. If an error is thrown from the function, it is caught and handled by the catch()
block. Within the catch
block, is where we simply send the errors to the client.
Why this Approach? Good question, this approach
- Get rid of unnecessary
try..catch
blocks in yourcontroller
files. - Stop using
return new Response(...)
every time you need to send an error response to the client. - Centralize tracking of all server-thrown errors in one location, opening up the option to utilize
sentry
for comprehensive error tracking. - Enhance the readability and maintainability of your codebase.
Validation Error (Zod) 🧪
Veloz kits using javascript as preferred language uses Zod
package for schema validation. This package is used to validate the request body, query params and headers. This package is used in the src/app/api/utils/zodValidation.ts
file.
It a reusable utility function which makes it easy to validate request body, query params and headers. It takes in a schema
and data
to validate, if the validation fails, it throws a VALIDATION_ERROR
which is handled by the CatchError()
middleware.
All related zod schema validation are stored within the src/app/api/utils/schema_validation.(ts)
Usage:
This utility function is meant to be used in the controller
files, for eg:
_11import ZodValidation from "../utils/zodValidation";_11import { registerSchema } from "../utils/schema_validation";_11_11export default class AuthController {_11 // register user (nextauth, jwt)_11 public async register(req: NextRequest) {_11 const payload = (await req.json()) as RegisterPayload;_11 // validate payload_11 await ZodValidation(registerSchema, payload, req.url);_11 }_11}
Sending Response 📦
How about sending response to client? well we've got you covered, we've created a utility class called sendResponse()
which is used to send response to the client, this function can be found in the src/app/api/utils/sendResponse.(ts)
file. This class exposes two methods namely error()
and success()
.
error()
- This method is used to send error response to the client.success()
- This method is used to send successfull response to the client.
Usage:
Since Nextjs app router expects an error response object to get returned,
always make sure to return the response object from the sendResponse()
function.
_10return sendResponse.error(_10 RESPONSE_CODE.INTERNAL_SERVER_ERROR,_10 "INTERNAL SERVER ERROR",_10 500,_10 err_10);