doc: finalize failure document
This commit is contained in:
parent
da8bbc5c9e
commit
4291fa832a
@ -1,21 +1,22 @@
|
|||||||
# Error handling with failure
|
# Error handling with failure
|
||||||
|
|
||||||
## What is failure
|
## What is failure
|
||||||
In each application and in each logic, there can be failure on the process and based on their complexity it can be few or many possilbe scenarios for these failures.
|
In each application and in each logic, there can be failures in the process, and based on their complexity, there can be a few or many possible scenarios for these failures.
|
||||||
|
|
||||||
In software development we always trying to have more controll on this failure to:
|
In software development, we always try to have more control over these failures to:
|
||||||
- Avoid possible bugs
|
|
||||||
- Help user to understand about the state of the application with proper messages
|
|
||||||
- Controll on the processes for some side effects
|
|
||||||
- Monitor the behavior of the application
|
|
||||||
|
|
||||||
So having a specific way of error handling for these failure to achieve all these requirements in our app, helps us to build more robust, trustable, and maintainable application.
|
Avoid possible bugs
|
||||||
|
Help users understand the state of the application with proper messages
|
||||||
|
Control processes for side effects
|
||||||
|
Monitor the behavior of the application
|
||||||
|
So, having a specific way of handling errors to achieve all these requirements in our app helps us build a more robust, reliable, and maintainable application.
|
||||||
|
|
||||||
Many frameworks provides their own ways to handle these failures which thet can name it as exceptions, failures or any other things, but for sure we shouldn't always depend our logics and apps to the behavior of the frameworks and besides there are many frameworks which doesn't provide error handling tools, so we should always have a specific and reliable way to handle our errors in all layers of the application.
|
Many frameworks provide their own ways to handle these failures, which they may call exceptions, failures, or other terms. But we shouldn't always depend on the behavior of frameworks for our logic and apps. Besides, many frameworks do not provide error handling tools, so we need to design a reliable architecture for the error handling in our application.
|
||||||
|
|
||||||
## Failure handling with base failure
|
## Failure handling with base failure
|
||||||
To have granular controll on the failure and have specific type for all errors we can use the inheritance and abstraction power of oop.
|
To have granular control over failures and define a specific type for all errors, we can use the power of inheritance and abstraction in OOP.
|
||||||
So we can define an abstract calsss as our base failure, which is our specific type of our failures in the application.
|
|
||||||
|
We can define an abstract class as our base failure, which serves as the specific type for all failures in the application.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default abstract class BaseFailure<META_DATA> {
|
export default abstract class BaseFailure<META_DATA> {
|
||||||
@ -28,10 +29,11 @@ export default abstract class BaseFailure<META_DATA> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
As you see it's just a simple abstract class which gets some metadata about details of error in any shape. But wait it's just starting of the story, we can have many ideas with this failure.
|
As you can see, it's just a simple abstract class that takes some metadata about the error details in any form. But wait, this is just the beginning of the story, we can explore many ideas with this failure.
|
||||||
|
|
||||||
## How to write a simple failure
|
## How to write a simple failure
|
||||||
So for creating a simple failure we can just define our failure in any domain for any scenaio which we need like this:
|
So, to create a simple failure, we can define our failure in any domain for any scenario we need, like this:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default class CreateUserFailure extends BaseFailure<{ userId: string }> {
|
export default class CreateUserFailure extends BaseFailure<{ userId: string }> {
|
||||||
constructor(metadata?: { userId: string }) {
|
constructor(metadata?: { userId: string }) {
|
||||||
@ -40,38 +42,53 @@ export default class CreateUserFailure extends BaseFailure<{ userId: string }> {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
So in our logics for creating user we can return specific tyep of failure for creating user.
|
So in our logics for creating user we can return specific type of failure for creating user.
|
||||||
|
|
||||||
## Combination with Functional programming
|
## Combination with Functional programming
|
||||||
Functional programming is a deep topic which we cannot cover it here for more details and learn about it you can watch these course or many courses and related books which exists on the web. But for this article we care about one of the most useful functors in functional programming and how failure can fit perfectly with failure. And this functor is either funtor.
|
Functional programming is a deep topic that we cannot fully cover here. For more details, you can check out various courses and books available online.
|
||||||
Either provides a data which is two parts, it's right answer and left answer. right answer is the type of the answer which we expect from either and left answer is exactly what we need as unexpected result.
|
|
||||||
You're gussing right this base failure will be our left answers for either functor.
|
However, for this article, we focus on one of the most useful functors in functional programming and how failure fits perfectly with it. This concept is the Either type.
|
||||||
|
|
||||||
|
Either is an algebraic data type (ADT) that represents computations that can return either a success or a failure. It consists of two possible values:
|
||||||
|
|
||||||
|
- Right(value): Represents a successful result.
|
||||||
|
- Left(error): Represents a failure or unexpected result.
|
||||||
|
|
||||||
|
You're guessing right, our base failure will serve as the Left value in Either, allowing us to handle errors in a structured and functional way.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
Either<
|
Either<
|
||||||
BaseFailure<unknown>,
|
BaseFailure<unknown>,
|
||||||
ResponseType
|
ResponseType
|
||||||
>
|
>
|
||||||
```
|
```
|
||||||
So as we always have specific type for handling unexpected resulsts, so we can define a new type for either in our app.
|
So as we always have specific type for handling unexpected results, so we can define a new type for either in our app.
|
||||||
```ts
|
```ts
|
||||||
export type ApiEither<ResponseType> = Either<
|
export type ApiEither<ResponseType> = Either<
|
||||||
BaseFailure<unknown>,
|
BaseFailure<unknown>,
|
||||||
ResponseType
|
ResponseType
|
||||||
>;
|
>;
|
||||||
```
|
```
|
||||||
So any othe either which for calling api we can use this either type for them.
|
So, for any API calls, we can use the Either type to handle both success and failure cases.
|
||||||
And also for async process we use TaskEither which is the same as either functor but for asynchronous process.
|
|
||||||
|
Additionally, for asynchronous processes, we use TaskEither, which works similarly to Either but is designed for handling asynchronous operations.
|
||||||
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
type ApiTask<ResponseType> = TaskEither<BaseFailure<unknown>, ResponseType>;
|
type ApiTask<ResponseType> = TaskEither<BaseFailure<unknown>, ResponseType>;
|
||||||
```
|
```
|
||||||
|
|
||||||
For example to get customers repository to handle all calling for customer api we can use this type for them.
|
For example, when creating a customer repository to handle all API calls for customers, we can use this type to manage success and failure cases.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default interface CustomerRepo {
|
export default interface CustomerRepo {
|
||||||
fetchList(query: string): ApiTask<Customer[]>;
|
fetchList(query: string): ApiTask<Customer[]>;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
And in the repo we can have this pipe to get customer data:
|
And in the repo we can have this pipe to get customer data:
|
||||||
|
|
||||||
|
> Note: In functional programming, a pipe is a composition of functions where the output of one function is passed as the input to the next, allowing for a clean, readable flow of data transformations.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
pipe(
|
pipe(
|
||||||
tryCatch(
|
tryCatch(
|
||||||
@ -83,11 +100,11 @@ pipe(
|
|||||||
map(this.customersDto.bind(this)),
|
map(this.customersDto.bind(this)),
|
||||||
) as ApiTask<Customer[]>;
|
) as ApiTask<Customer[]>;
|
||||||
```
|
```
|
||||||
Pipe is just a pipe of process and operations which we make on the data to shape the whole process.
|
As you can see, in the try-catch block, which is the constructor of ApiEither, we define the right response in the first callback and the failure in the second callback argument.
|
||||||
|
|
||||||
As you see in try catch which is constructor of a ApiEither we defined our right response from first callback and our failure as the second callback argument.
|
failureOr is just a helper function that takes an error and converts it into a specific failure type, NetworkFailure in this example.
|
||||||
And failureOr is just a helper to get a error and turn to some specific failure __which is NetworkFailure in this example__
|
|
||||||
So in the process of fetching customer we know the unexpected result, always will be a speicfic type.
|
This ensures that during the process of fetching customer data, we always know the unexpected result will be of a specific type.
|
||||||
```ts
|
```ts
|
||||||
export function failureOr(
|
export function failureOr(
|
||||||
reason: unknown,
|
reason: unknown,
|
||||||
@ -99,27 +116,30 @@ export function failureOr(
|
|||||||
return failure;
|
return failure;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
So in the process of fetching customer we know the unexpected result, always will be a speicfic type.
|
||||||
So in any layer we can get the failure do some logics on left response based on its metadata and turn the failure shape to any other failure shape and use it for different purposes.
|
So in any layer we can get the failure do some logics on left response based on its metadata and turn the failure shape to any other failure shape and use it for different purposes.
|
||||||
|
|
||||||
## Usecases of this idea
|
## Usecases of this idea
|
||||||
|
|
||||||
### Monitoring for failures
|
There are many situations where, if an important process encounters problems, we want to have control over it. We need to know when and why these issues happened and store that information in one of the monitoring tools.
|
||||||
There are many situations that when some important process had some problems we wanna have controll on it, to know when and why these things happened and store it in one of the monitoting tools.
|
|
||||||
|
|
||||||
For example on getting CreateUserFailure in repository layer, we can send a log with specific time and use parameters data to any logging or monitoring tools.
|
For example, when a CreateUserFailure occurs in the repository layer, we can send a log with the specific time and relevant parameter data to any logging or monitoring tool.
|
||||||
|
|
||||||
### Monitoring on bugs with dev failures
|
### Monitoring on bugs with dev failures
|
||||||
There are many situations specifally in frontend appications which some unexpected behavior happens from the development mistakes and bugs for example by getting some bugs or data changes in apis, it's possible to face with unexpected behaviors and we wanna show some specific message or redirect user to error page with descent message. On top of in frontend applications they cannot get the log in this situation as it's happened in the user's system, so they can send the metadata as a log to one api if they face with dev failures.
|
There are many situations, especially in frontend applications, where unexpected behavior occurs due to development mistakes or bugs. For example, when bugs or data changes in APIs happen, it's possible to face unexpected behaviors. In such cases, we want to show a specific message or redirect the user to an error page with a clear message.
|
||||||
|
|
||||||
To acheive this we can simply define another abstract failure like this:
|
Additionally, in frontend applications, logs may not be directly available in these situations, as the issue occurs on the user's system. To handle this, we can send metadata as a log to an API when encountering development failures.
|
||||||
|
|
||||||
|
To achieve this, we can simply define another abstract failure like this:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default abstract class BaseDevFailure<
|
export default abstract class BaseDevFailure<
|
||||||
META_DATA,
|
META_DATA,
|
||||||
> extends BaseFailure<META_DATA> {}
|
> extends BaseFailure<META_DATA> {}
|
||||||
```
|
```
|
||||||
As you see it's just another failure which is extend from base failure.
|
As you can see, it’s just another failure that extends from the base failure.
|
||||||
So for example in some part of application which should send some arguments into domain layer and as these arguments are dynamic and possible to send unexpected data we can define one dev failure for this situation like this:
|
|
||||||
|
For example, in some parts of the application, when sending dynamic arguments into the domain layer, there's a possibility of sending unexpected data. In such situations, we can define a specific development failure like this:
|
||||||
```ts
|
```ts
|
||||||
export default class ArgumentsFailure<
|
export default class ArgumentsFailure<
|
||||||
META_DATA,
|
META_DATA,
|
||||||
@ -132,14 +152,13 @@ export default class ArgumentsFailure<
|
|||||||
So we can consider this scenario in our logics and facing with this failure we can make a log request to our log api even from frontend applications, so on facing with this situation they can show a descent message to user to contact to support team at the same time they store the bug log to have full controll on these situations.
|
So we can consider this scenario in our logics and facing with this failure we can make a log request to our log api even from frontend applications, so on facing with this situation they can show a descent message to user to contact to support team at the same time they store the bug log to have full controll on these situations.
|
||||||
|
|
||||||
### Manage translations and error messages with failure
|
### Manage translations and error messages with failure
|
||||||
With this idea we can move one step beyound error handling and even handle translation and showing related messages in frontend applications in an automatic way.
|
With this approach, we can go a step further than just error handling and even manage translations and display related messages in frontend applications automatically.
|
||||||
|
|
||||||
For each process and scenario we should define specific failure and also at the same time for each one of them we should show specific message in specific language based on selected language by the user.
|
For each process and scenario, we should define a specific failure. At the same time, for each failure, we should display a corresponding message in the selected language based on the user's preference.
|
||||||
|
|
||||||
So we can use this idea and automate these process together.
|
We can use this idea to automate both the error handling and message translation process.
|
||||||
|
|
||||||
To achieve this requirement we can pass a unique string key from constructor based on the failure scenario.
|
To achieve this, we can pass a unique string key from the constructor based on the failure scenario. Our base failure will look like this:
|
||||||
So our base failure will turn like this:
|
|
||||||
```ts
|
```ts
|
||||||
export default abstract class BaseFailure<META_DATA> {
|
export default abstract class BaseFailure<META_DATA> {
|
||||||
private readonly BASE_FAILURE_MESSAGE = "failure";
|
private readonly BASE_FAILURE_MESSAGE = "failure";
|
||||||
@ -166,13 +185,15 @@ export function makeFailureMessage(message: string, key: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
As you see we have a message property, which has
|
As you can see, we have a message property, which contains `BASE_FAILURE_MESSAGE`, the base key for all failure messages. It also accepts a key from the constructor, and with the makeFailureMessage function, it concatenates the new key with the message, shaping a unique message for each failure.
|
||||||
`BASE_FAILURE_MESSAGE` which is the base key for all failure messages. Also it gets key from constructor and with makeFailureMessage function concat the new key with the message and shape new message for each failre.
|
|
||||||
|
Each failure can have its own key passed from its constructor.
|
||||||
|
|
||||||
|
In the end, we can have a chained message key that we can use as the message key for each failure.
|
||||||
|
|
||||||
|
For example, for a failure like `UserAlreadyExistsFailure`, we can have a parent failure for all user domain failures, like this:
|
||||||
|
|
||||||
Also each failure can get their own key from their constructors.
|
|
||||||
So at the end of the day we can have a chained message key that we can use it as a message key.
|
|
||||||
|
|
||||||
For example for a failure like `UserAlreadyExistsFailure` we can have a parent failure for all user domain failures like this:
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default class UserFailure extends BaseFailure {
|
export default class UserFailure extends BaseFailure {
|
||||||
@ -181,7 +202,7 @@ export default class UserFailure extends BaseFailure {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
and now we can make our failure:
|
and now we can define our failure:
|
||||||
```ts
|
```ts
|
||||||
export default class UserAlreadyExistsFailure extends UserFailure {
|
export default class UserAlreadyExistsFailure extends UserFailure {
|
||||||
constructor() {
|
constructor() {
|
||||||
@ -191,7 +212,7 @@ export default class UserAlreadyExistsFailure extends UserFailure {
|
|||||||
```
|
```
|
||||||
so the result of message for `UserAlreadyExistsFailure`, will be `failure.user.alreadyExists`.
|
so the result of message for `UserAlreadyExistsFailure`, will be `failure.user.alreadyExists`.
|
||||||
|
|
||||||
At the same time in other place in our project we're using langkey object to specify translation key and this object, like failure follows domain and folder structure to specify lang key.
|
At the same time, in another part of our project, we're using a langKey object to specify the translation key. This object, like the failure structure, follows the domain and folder structure to specify the language key.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const langKey = {
|
const langKey = {
|
||||||
@ -203,7 +224,7 @@ const langKey = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
So we can use our failure message key to get lang key and by passing it to translation method we can get translated failure message and make a automated process to show error message based on failure that we get.
|
So, we can use our failure message key to retrieve the language key. By passing it to the translation method, we can get the translated failure message and automate the process of displaying the error message based on the failure we encounter.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const usecaseResponse = await getUsersUsecase() as Promise<Either<BaseFailure, User[]>>
|
const usecaseResponse = await getUsersUsecase() as Promise<Either<BaseFailure, User[]>>
|
||||||
@ -215,3 +236,11 @@ const translatedFailureMessage = t(usecaseResponse.left.message)
|
|||||||
```
|
```
|
||||||
This is the final version, class diagram for our failur architecture:
|
This is the final version, class diagram for our failur architecture:
|
||||||

|

|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
In this article, we've explored how to handle failures effectively in software applications by combining error handling with functional programming concepts like the Either type.
|
||||||
|
|
||||||
|
Furthermore, by integrating these failure handling mechanisms with automated processes for translating and displaying error messages, we create a more seamless experience for users, no matter the scenario. This approach not only improves the user experience by offering clear and context-specific messages, but it also provides valuable insights through monitoring and logging, enabling teams to quickly address issues.
|
||||||
|
|
||||||
|
Ultimately, this architecture supports building more robust, maintainable, and user-friendly applications, which I have used in many of my own projects, especially in frontend ones.
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user