Following is an implementation of the result monad, this monad can be used in place of throwing errors:
Result Type:
class Result<T>{
private constructor(success: boolean, content: T, error: IErrorResponse | null) {
this.success = success;
this.error = error;
}
static success<T>(content: T) {
return new Result<T>(true, content, null);
}
static void() {
return new Result(true, null, null);
}
static failure(error: IErrorResponse)
{
if (!error)
{
throw new Error('error is required')
}
return new Result(false,null, error);
}
success: boolean;
error: IErrorResponse | null;
}
Error Response:
interface IErrorResponse{
code: string;
message: string;
}
class ErrorResponse implements IErrorResponse{
constructor(code: string, message: string) {
this.code = code;
this.message = message;
}
public code: string;
public message: string;
}