简体   繁体   中英

The type caught or thrown must be derived from System.Exception

Do I need a constraint in the following code to solve the above compiler error:

private T GetResponse<T, TError>(HttpResponseMessage response)
{
    if (response.IsSuccessStatusCode)
    {
        return response.Content.ReadAsAsync<T>().Result;
    }

    else
    {
        if (response.StatusCode == HttpStatusCode.BadRequest)
        {
            var ex = response.Content.ReadAsAsync<TError>().Result;
            throw ex;
        }
    }

    throw new NotImplementedException();
}

I'm calling the above as follows:

public int MyMethod(string param)
{
    var response = client.PostAsJsonAsync(url, param).Result;
    return GetResponse<int, MyException>(response);
}

MyException does derive from System.Exception , however I get the above compiler error. Is a constraint needed?

将方法更改为:

private T GetResponse<T, TError>(HttpResponseMessage response) where TError : Exception

Yes, the throw statement requires the type to derive from Exception . A constraint would fix this.

private T GetResponse<T, TError>(HttpResponseMessage response)
    where TError : Exception

在方法定义中添加where TError : Exception

During compile-time it´s not clear that ex actually is an exception. The compiler only knows that it is of type TError which may or may not implement Exception . Although you provide the type when calling GetResponse<int, MyException>(response) the compiler does not have any chance that TError is allways of that given type - so within your generic method there is no knowledge on that type at all. What should the compiler do if you´d about to write something like GetResponse<int, MyType>(response) instead?

As the throw -statement expects an instance of Excpetion you´ll need a type-constraint for TError as you´ve already supposed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM