Im playing abit with the .NET minimal API. Trying to catch this exception when Im passing "Price" as a string I've got my DTO as follows:
public record TransactionCreateDto
{
public string Description { get; init; } = String.Empty;
public string Store { get; init; } = String.Empty;
public double Price { get; init; }
public string Date { get; init; } = String.Empty;
public int PaymentTypeId { get; init; }
public int CategoryId { get; init; }
public bool Seen { get; init; }
}
Here is the flow:
...
app.MapPost("/transactions", TransactionsAPI.InsertTransaction);
...
And he insert transaction function:
public static async Task<IResult> InsertTransaction(TransactionCreateDto transactionDto, ITransactionRepository repo)
{
try
{
...
}
catch (Exception ex)
{
...
}
}
Im sure there is a correct way to catch this exception. Thanks alot!
CodePudding user response:
Since the exception is happening before your function is getting called, I prefer the following approach. It's not 100% by the playbook, but gives much more flexibility.
Lets assume this is your original signature:
public static async Task<IResult> InsertTransaction(TransactionCreateDto transactionDto)
So instead of getting the DTO, try to get JObject.
public static async Task<IResult> InsertTransaction(Jobject json)
{
try
{
var m = JsonConvert.DeserializeObject<TransactionCreateDto>(json);
}
catch(SomeSpecificException es)
{
}
catch(Exception e)
{
}
}
CodePudding user response:
If the situation you are trying to handle is that passed string is a valid number (i.e. you want to allow this), one option is to allow the serializer to handle such cases by configuring it (see customizing json binding doc and JsonNumberHandling
enum):
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
});
Otherwise depending on the use case you can either handle the request parsing manually (custom serializer, BindAsync
convention, or just from the request) or use custom error handler (if you want just to process the error in some custom way).