4 Comments
User's avatar
Nguyễn Lê Tấn Nghiệp's avatar

When I use this pattern, will my response status code be affected as well. For examples, if (item == null) return Result<Item>.Failure($"Item with ID {id} not found"); Will this response status code is 404 or it is going to be 200 with the Failure message

Expand full comment
DotNet Full Stack Dev's avatar

Thanks for raising this one, its little extension to this post.. anyways you can follow these steps to return error message along with status code

public class Result<T>

{

public bool IsSuccess { get; }

public string ErrorMessage { get; }

public T Value { get; }

public int StatusCode { get; }

private Result(T value, bool isSuccess, string errorMessage, int statusCode)

{

Value = value;

IsSuccess = isSuccess;

ErrorMessage = errorMessage;

StatusCode = statusCode;

}

public static Result<T> Success(T value)

=> new Result<T>(value, true, null, 200);

public static Result<T> Failure(string errorMessage, int statusCode = 400)

=> new Result<T>(default, false, errorMessage, statusCode);

}

var result = Result<string>.Success("Data processed successfully");

// result.StatusCode will be 200

var errorResult = Result<string>.Failure("Invalid input", 400);

// errorResult.StatusCode will be 400

var serverErrorResult = Result<string>.Failure("Unexpected error", 500);

// serverErrorResult.StatusCode will be 500

Expand full comment
Anil Kumar Khandei's avatar

Informative!!

Expand full comment
DotNet Full Stack Dev's avatar

Thanks, Great to hear from @codexpert!

Expand full comment