Skip to content

Instantly share code, notes, and snippets.

@pauloafpjunior
Last active February 15, 2022 06:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauloafpjunior/053375a6821d7e305a31d13d0b12345c to your computer and use it in GitHub Desktop.
Save pauloafpjunior/053375a6821d7e305a31d13d0b12345c to your computer and use it in GitHub Desktop.
Error handling in TypeScript: an alternative approach
// Value object
class CityName {
static readonly MIN_LEN_NAME: number = 3
static readonly MAX_LEN_NAME: number = 100
private constructor(private _name: string) { }
// Factory method with validation rules
static create(name: string): [CityName, Error] {
if (name == null || name.trim().length < CityName.MIN_LEN_NAME || name.trim().length > CityName.MAX_LEN_NAME) {
return [
null,
new InvalidNameError(name)
];
}
// No validation errors
return [new CityName(name), null]
}
get name(): string { return this._name; }
}
// Validation error
class InvalidNameError extends Error {
constructor(name: string) {
super(`The name "${name}" is not valid!`)
}
}
// Input
const text = prompt('Type the city name: ');
// How to use
const [city, error] = CityName.create(text);
if (error != null) {
alert(`Error: ${error.message}`);
} else {
alert(`Welcome to ${city.name}`)
}

Test on Playground

This approach was used in a clean architecture example, available here

@kasvith
Copy link

kasvith commented Dec 17, 2020

Your approach is similar to golang's default method :)

@pauloafpjunior
Copy link
Author

Your approach is similar to golang's default method :)

Yes it is!! :)

@4e1e0603
Copy link

Nice! The pros is that you dont have to define a custom Result class. The downside is that cannot chain errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment