Skip to content

Latest commit

 

History

History
27 lines (23 loc) · 1.05 KB

File metadata and controls

27 lines (23 loc) · 1.05 KB

Create a Failed Result or Result<TValue> instance from an exception

A Failed Result instance can be created from an exception by calling corresponding static method with an exception input parameter for each FailureType, or can be left to implicit operator which creates a Failed Result with FailureType CriticalError by default.

Exception object is converted to an Error object and added to Error collection of Failure.

public async Task<Result<GetBookByIdResponse>> GetBookById(GetBookByIdRequest req, CancellationToken ct)
{
    try
    {
        var entity = await db.Books.FirstOrDefaultAsync(b => b.Id == req.Id, ct);

        return entity is null ?
          Result<GetBookByIdResponse>.NotFound() :
          Result.Ok(new GetBookByIdResponse(
            Id: entity.Id,
            Title: entity.Title,
            Author: entity.Author,
            Price: entity.Price));
    }
    catch (Exception ex)
    {
        return ex;
    }
}