I have a simple Class with 1 property and validation on set.
I expect System.UriFormatException
to be thrown, but System.Reflection.TargetInvocationException
is thrown on invalid uri.
public class MyClass
{
private string _baseUrl;
public string BaseUrl
{
get => _baseUrl;
set
{
if (!Uri.IsWellFormedUriString(value, UriKind.Absolute))
{
throw new UriFormatException($"Host is not valid Uri: {BaseUrl}");
}
_baseUrl = value;
}
}
}
If I change this class so it looks like as is below and I call Validate()
on the object I have created, then I have System.UriFormatException
thrown, why is there this difference. Ideally, I would like to throw System.UriFormatException
with the first snippet. I have a feeling that is caused because is thrown during object instantiation but would like to know more about it.
public class MyClass {
public string BaseUrl { get; set; }
public void Validate () {
if (!Uri.IsWellFormedUriString (BaseUrl, UriKind.Absolute)) {
throw new UriFormatException ($"Host is not valid Uri: {BaseUrl}");
}
}
}
I am changing the code, so that exception is thrown during instantiation of the object, and not later with Validate()
. That allows me to save few lines, and also the fact that Validate()
maybe forgotten to be called. Also, I am aware of ValidationAttribute
class and I am not interested in it.
question from:
https://stackoverflow.com/questions/65943867/why-system-reflection-targetinvocationexception-is-thrown-instead-of-system-urif 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…