-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Asynchronous calls typically involve some kind of I/O, such as network requests or disk operations, both of which are prone to errors and can fail in all sorts of ways. Oftentimes, especially when in a Clean Architecture, you want to hide implementation details - in this case errors - from the rest of the application.
In order to do so, it is commonly considered good practice to throw more "abstract" errors, so maybe a custom RemoteFooProviderError
instead of just letting the error thrown by the used HTTP client bubble up. This is frequently combined with adding some additional logic like so:
class Foo {
public async getFooFromRemoteSource(id: number): Promise<Foo> {
let response: FooResponse
try {
response = await this.httpClient.get(`/foo/${id}`)
} catch (error) {
if (error instanceof HttpClientError) {
if (error.statusCode === 404) {
throw new FooNotFoundError(id)
}
throw new FooRemoteSourceError(error)
}
throw new UnexpectedFooRemoteSourceError(error)
}
return new Foo(response.data)
}
}
While there is nothing wrong with that approach per se, it quickly becomes tedious (and increasingly annoying to maintain) once you have multiple methods that share the same error handling boilerplate. It is also not particularly nice-looking code because the signal-to-noise-ratio is fairly poor.
This is the problem this module sets out to simplify:
class Foo {
@HandleError(
{
action: HandlerAction.MAP,
scope: HttpClientError,
predicate: error => (error as HTTPError).statusCode === 404,
callback: (_error, id) => new FooNotFoundError(id),
}, {
action: HandlerAction.MAP,
scope: HttpClientError,
callback: error => new FooRemoteSourceError(error),
}, {
action: HandlerAction.MAP,
callback: error => new UnexpectedFooRemoteSourceError(error),
},
)
public async getFooFromRemoteSource(id: number): Promise<Foo> {
const response = await this.httpClient.get(`/foo/${id}`)
return new Foo(response.data)
}
}