ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
888 stars 107 forks source link

[Question] How to handle unsuccesful results at API level #171

Closed dkamau closed 6 months ago

dkamau commented 8 months ago

For example, if I sent back a conflict from my handler;

return Result.Conflict($"Contributor with name {request.NewName} already exists!");

How will I report that to the user at the API level?

public override async Task HandleAsync(
  CreateContributorRequest request,
  CancellationToken cancellationToken)
{
  var result = await _mediator.Send(new CreateContributorCommand(request.Name!,
    request.PhoneNumber), cancellationToken);

  if (result.IsSuccess)
  {
    Response = new CreateContributorResponse(result.Value, request.Name!);
    return;
  }
  // TODO: Handle other cases as necessary

  if(result.Status == Ardalis.Result.ResultStatus.Conflict)
  {
    Response = ? "What code goes here??";
    return;
  }
}

I tried this but it does not report as expected

if(result.Status == Ardalis.Result.ResultStatus.Conflict)
{
  Response = Result<CreateContributorResponse>.Conflict(result.Errors.ToString());
  return;
}
KyleMcMaster commented 8 months ago

@dkamau Are you using FastEndpoints?

dkamau commented 8 months ago

@KyleMcMaster Yes I am.

KyleMcMaster commented 8 months ago

We've discussed adding FastEndpoints support in issue #157

sunecko commented 7 months ago

i using fast endpoit around six months on my work , i think it's a great idea add FE support to Results. I wanna participate

KyleMcMaster commented 7 months ago

There is work being done to provide support for FastEndpoints similar to the functionality for ASP.NET Core support. Consider 👍 'ing the issue in #175 if you'd like to see this implemented.

ardalis commented 6 months ago

See this comment from #175:

FastEndpoint already has a SendResultAsync() to send any IResult instance produced by the Results static class in Minimal APIs. So simply you can call something like this: await SendResultAsync(result.ToMinimalApiResult()); More info: https://fast-endpoints.com/docs/misc-conveniences#send-methods

I'm assuming that either this fixes the immediate issue or, if not, that #175 will do so, so I'm going to close this now. Re-open if you still need to.