-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[CHE-198] Create BE Error Handling Docs #157
Merged
brok3turtl3
merged 7 commits into
dev
from
CHE-198/subtask/Create-BE-Error-Handling-Docs
Jun 28, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
212639b
begin readme
seantokuzo d8fcd65
custom errors docs started
seantokuzo da5dc92
draft 1
seantokuzo 563f1af
wording change
seantokuzo d5bc1ad
wording change
seantokuzo 956331f
wording change
seantokuzo 9b9b5ba
updates to ValidationError
seantokuzo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
# Error Handling | ||
|
||
## Quick Links | ||
|
||
- [Back End Error Handling](#backend) | ||
- [Express Async Errors](#async-errors) | ||
- [Custom Error Classes](#custom-errors) | ||
- [Global Error Handler](#global-error-handler) | ||
- [Front End Error Handling](#frontend) | ||
|
||
<hr> | ||
|
||
<a id="backend"></a> | ||
|
||
## Back End Error Handling | ||
|
||
<a id="async-errors"></a> | ||
|
||
#### express-async-errors | ||
|
||
Codehammers makes use of the [express-async-errors](https://www.npmjs.com/package/express-async-errors) package to simplify error handling in asynchronous route handlers and middlewares. This package enables us to simply throw errors instead of manually passing error objects to Express's `next` function. An example would be: | ||
|
||
``` | ||
/* with express-async-errors */ | ||
const middleware = async (req: Request, res: Response) => { | ||
throw new Error('This error will automatically be caught and passed to next') | ||
} | ||
``` | ||
|
||
whereas typically we would have to do this: | ||
|
||
``` | ||
/* without express-async-errors */ | ||
const middleware = async (req: Request, res: Response, next: NextFunction) => { | ||
next({ | ||
message: 'This error was manually passed to next' | ||
}) | ||
} | ||
``` | ||
|
||
Using `express-async-errors` eliminates the need for try/catch blocks and allows us to simply throw errors where needed without manually invoking `next` | ||
|
||
**How it works** | ||
The Express framework automatically catches errors thrown in synchronous route handlers and middlewares. However, in the case of asynchronous route handlers and middlewares, Express requires us to manually call `next`, passing in an error object (or anything besides the string `'route'`), in order to invoke the global error handling middleware. | ||
|
||
The [express-async-errors package wraps](https://github.com/davidbanham/express-async-errors/blob/master/index.js) Express's Router's [Layer object's](https://github.com/expressjs/express/blob/master/lib/router/layer.js) `handle` property, enabling errors thrown in asynchronous route handlers and middlewares to automatically be caught and passed to `next`. We simply require/import this package once (in `server/app.ts`) and it's functionality is enabled. | ||
|
||
A similar approach would require defining our own wrapper such as: | ||
|
||
``` | ||
const catchAsync = (fn) => { | ||
return (req, res, next) => { | ||
fn(req, res, next).catch(next) | ||
} | ||
} | ||
``` | ||
|
||
we would then have to wrap every route handler and middleware in this catchAsync function to automatically catch errors and pass them to next: | ||
|
||
``` | ||
const middleware = catchAsync(async (req, res) => { | ||
throw new Error('Oops, something went wrong') | ||
}) | ||
``` | ||
|
||
Much nicer not having to manually wrap every route handler and middleware! | ||
|
||
<a id="custom-errors"></a> | ||
|
||
#### Custom Error Classes | ||
|
||
Codehammers uses custom error classes for handling the most common types of errors that occur on the server. These classes can be found in the `server/errors/` directory. These error classes and their corresponding status codes are: | ||
|
||
- `BadRequestError` : 400 (requires a `message` argument when instantiated) | ||
- `DatabaseConnectionError` : 500 | ||
- `InternalError` : 500 | ||
- `NotAuthorizedError` : 401 | ||
- `NotFoundError` : 404 | ||
- `RequestValidationError` : 400 (requires an array of `ValidationError`s as an argument when instantiated - see [below](#request-validation-error)) | ||
|
||
Each of these error classes extend our `CustomError` abstract class (which itself extends JavaScript's built-in `Error` object). This abstract class cannot be instantiated, but is used to enforce a structure for our custom error classes: requiring a `statusCode` property, a `message` property, as well as a `serializeErrors` method. The `serializeErrors` method ensures that errors sent back to the client are consistently formatted as an array of objects, each object containing a `message` property and an optional `field` property - used for validation errors. | ||
|
||
<a href="request-validation-error"></a> | ||
|
||
##### RequestValidationError | ||
|
||
Another custom utility error class is `ValidationError`. This error is for user inputs that fail validation, such as an invalid email, or a password that is too short. | ||
|
||
When validating multiple user inputs, we create an array for validation errors and push in a `ValidationError` for each failed validation. We then throw a `RequestValidationError` if this array contains any `ValidationError`s. An example of this could be: | ||
|
||
``` | ||
const createUser = async (req: Request, res: Response) => { | ||
const { email, password } = req.body | ||
const validationErrors: ValidationError[] = [] | ||
if (!email) { | ||
validationErrors.push(new ValidationError('Please provide a valid email', 'email')) | ||
} | ||
if (!password) { | ||
validationErrors.push(new ValidationError('Please provide a valid password', 'password')) | ||
} | ||
if (validationErrors.length) { | ||
throw new RequestValidationError(validationErrors) | ||
} | ||
// continue if input validation checks pass... | ||
} | ||
``` | ||
|
||
`ValidationError`s include a relevant `message` for the user, and the `field` representing which input failed validation, passed as arguments when instantiating a `ValidationError`. | ||
|
||
Having the ability to collect and send back multiple errors for each validation failure helps our front end developers relay useful information to the user about which inputs were invalid and need fixing. | ||
|
||
<a href="global-error-handler"></a> | ||
|
||
#### Global Error Handler | ||
|
||
We are currently migrating our error handling to make use of `express-async-errors` and our custom error classes. While this migration is ongoing, we still need to handle error objects that have been manually passed to Express's `next` function. Our global error handler (`server/middleware/errorHandler.ts`) is setup to handle both of these cases, while still sending back consistently formatted errors. If an error is neither a custom error class or manually caught error object, we send back a generic `InternalError` with `500` status code. | ||
|
||
<hr> | ||
|
||
<a id="frontend"></a> | ||
|
||
## Front End Error Handling | ||
|
||
TBD |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@seantokuzo TBD! 🎉
Great write doc - Thanks!