Home > Back-end >  Force exception on missing non-null properties
Force exception on missing non-null properties

Time:02-22

I have a simple record like this:

public record Filter
{
    public int Id { get; init; }
}

The property is explicitly not non-null. I want the framework to throw an exception when the type Filter is initialized without the ID. How do I do that?

Right now it just puts "0" as a default value and I have no idea of the broken initialization.

CodePudding user response:

Use a constructor:

public record Filter(int Id);

Now, you will get compiler errors if it is not explicitely given an Id. That's preferable to runtime exceptions anyway.

CodePudding user response:

I searched for a way that works with [ApiController], so the above doesn't work for me (but I didn't specify that, because I didn't know it would be different). So if the validation is for REST, the accepted answer won't work, the right way is:

public record Filter
{
    [Required]
    public int? Id { get; init; }
}

(Note that the int must be nullable, else the framework will default it to 0 and the required validation will never be done.)

With that setup, the endpoint will automatically return HTTP code 400 if the required field is missing.

  • Related