Typescript Exception Free Function Error Handling

Ole Ersoy
2 min readOct 1, 2021

--

Image by vujicivana from Pixabay

Updated Article

There’s an updated version of this article here:

Scenario

In this article:

We implemented the median function per the illustration of the method used to calculate it.

Here we will be adding error handling without using exceptions.

Approach

Error Function Type

Error strings will be created by functions that have the signature:

export type MessageFunctionType = (args?: string[]) => string;

Result Object

We’ll create a class to contain the result and errors if there are any.

/**
* Generic Result class.
*/
export class Result<E> {
constructor(public value: E | undefined,public error?: MessageFunctionType,public message?: string) {}}

In the event of an error the error property is assigned the function of type MessageFunctionType . The error property can be used in a switch statement to select the type of error that occurred.

Errors

We will define two types of errors. The first indicates that no array was passed in to the median function. The second indicates that one of the values in the array was not a number:

export interface IMedianErrors {
ARRAY_ARGUMENT_NOT_DEFINED: MessageFunctionType;
ARRAY_VALUE_NOT_A_NUMBER: MessageFunctionType;
}

And the implementation for the interface looks like this:

export const MEDIAN_ERRORS: IMedianErrors = 
{
ARRAY_ARGUMENT_NOT_DEFINED: (arr?: string[]) => {
return `The array argument for the median function was missing.`;
},
ARRAY_VALUE_NOT_A_NUMBER: (arr?: string[]) => {
return `The array ${ arr && arr.toString() } contains values that are not numbers.`;
}
};

Median Function Implementation

We are now communicating both the result and any errors that occurred using aResult instance:

Result Handler

We’ve implemented a basic result handler with a switch statement like this. Note that we are using the expression used to determine which case in the switch statement that should be invoked:

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet