Better Error Types
Get familiarized with the improvement in error handling in the reservation application.
We'll cover the following...
Improvement in error handling
Notice that we’ve been putting our errors in strings throughout this course, which is OK for smaller projects. Strings are far from ideal, though. The reasons for this are probably familiar by now. Strings are too generic and allow for a very wide range of information. We know little about what will be contained inside them and our compiler is similarly confused.
We’ll again use the Retrieve Lambda for this example. Let’s first add some types:
export type ClientError = {readonly type: 'ClientError',readonly message: string,}export type ServerError = {readonly type: 'ServerError',readonly message: string,}export type ErrorResponse = ClientError | ServerError
We’ve seen the code above before under various names. Our error is a sum
type. It is either a ClientError
or a ServerError
, nothing else. It consists of a type (otherwise, we can’t distinguish our errors) and a message
. Everything is readonly
. We generally don’t want to change our message (and certainly not our type) once it’s been created. We also need a way to build these errors, which we’ll add to our responses.
export const clientError = (message: string): ErrorResponse => {return {type: 'ClientError',message,};}export const serverError = (message: string): ErrorResponse => {return {type: 'ServerError',message,};};export const mapErrorToResponse = (err: ErrorResponse) => {return () => new Promise((resolve) => {switch (err.type) {case 'ClientError':return resolve(badRequestResponse(err.message));case 'ServerError':return resolve(internalServerErrorResponse(err.message));default:const _exhaustiveCheck: never = err;return _exhaustiveCheck;}});};
The last function is the interesting one. It provides a way to map our errors to what we’ll eventually give back to the user, in the shape of an HTTP response. If we have a client error, we’ll return a bad request (400). If it’s a server error we’re dealing with, it’s an internal server error (500). Because we’re using a sum type, we can once again use an exhaustiveness check to make our code more secure. If we do not deal with a specific error, it will cause the compiler to complain. ...