Skip to content

InvalidOperationException: Cannot return as T0 as result is T2 #188

@MrYossu

Description

@MrYossu

Just getting started with this excellent package, so please forgive me if I'm doing something stupid.

I have an API, and want to create a response type that will indicate if the request was successful (in which case we return the data requested), if the specified object wasn't found, or if there was a server error.

I created the following...

public class ApiResponse<T>(OneOf<Error<string>, NotFound, T> input) : OneOfBase<Error<string>, NotFound, T>(input) {
  public static implicit operator ApiResponse<T>(Exception ex) => new(new Error<string>(ex.Message));
}

This mostly works fine, but throws an exception if the data to be returned is a plain string, as in this rather dumb test case...

    app.MapGet("/testapi-time", () =>
      new ApiResponse<string>(DateTime.Now.ToLongTimeString()));

In this case, I get the exception shown in the subject line. I guess this is because both the data and the generic type of Error are string, so it doesn't know which to use, but could be way out here.

I guess I could get around this by declaring the type by inheriting from OneOfBase<Error<string>, NotFound, Success<T>>, but that makes the code more verbose for the few cases when I would be returning string data.

Anyone able to advise? Thanks

Update: I just tried changing the endpoint to return a DateTime instead of a string...

    app.MapGet("/testapi-time", () =>
      new ApiResponse<DateTime>(DateTime.Now));

...and got the same exception, so it looks like my guess above was wrong.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions