fail

Return fail

When processing is failure

return Result.fail<T, F>(/* your error message */);

T: first generic type refer to the value to return in success case.

F: second one refer to the error type to return in failure case. By default is string

It do not throw error and return an object with error message and result status

const result = Result.fail<any>("error message");

console.log(result)
> Result {
    isSuccess: false, 
    isFailure: true, 
    error: "error message", 
    _value: null,
    statusCodeNumber: 422,
    statusCode: "UNPROCESSABLE_ENTITY"
}

You can check if it has returned an error and also get the error message

const result = Result.fail<any>("error message");

console.log(result.isFailure)
> true

console.log(result.error)
> "error message"

Provide status for infra

const simulateError = (message: string): Result<void> => {
    try {
      throw new Error(message);
    } catch(error){
      return Result.fail<void>(error.message, "SERVICE_UNAVAILABLE");
    }
}


// get result
const result = simulateError("Error simulation");

console.log(result.isSuccess);
> false

console.log(result.statusCode);
> "SERVICE_UNAVAILABLE"

console.log(result.statusCodeNumber);
> 503

console.log(result.error);
> "Error simulation"
// Available status error
	
	MULTIPLE_CHOICES = 300,
	MOVED_PERMANENTLY = 301,
	FOUND = 302,
	SEE_OTHER = 303,
	NOT_MODIFIED = 304,
	USE_PROXY = 305,
	UNUSED = 306,
	BAD_REQUEST = 400,
	UNAUTHORIZED = 401,
	PAYMENT_REQUIRED = 402,
	FORBIDDEN = 403,
	NOT_FOUND = 404,
	METHOD_NOT_ALLOWED = 405,
	NOT_ACCEPTABLE = 406,
	PROXY_AUTHENTICATED_REQUIRED = 407,
	REQUEST_TIMEOUT = 408,
	CONFLICT = 409,
	GONE = 410,
	LENGTH_REQUIRED = 411,
	PRECONDITION_FAILED = 412,
	REQUEST_ENTITY_TOO_LARGE = 413,
	UNSUPPORTED_MEDIA_TYPE = 415,
	UNPROCESSABLE_ENTITY = 422,
	INTERNAL_SERVER_ERROR = 500,
	NOT_IMPLEMENTED = 501,
	BAD_GATEWAY = 502,
	SERVICE_UNAVAILABLE = 503,
	GATEWAY_TIMEOUT = 504,
	

Default error status if you do not provide one, is "UNPROCESSABLE_ENTITY" = 422

Last updated