I have a C# WebAPI project with controller/service/repository structure. Most of my controller methods call a service method which then calls a repository method to access the DB. If one of the parameters from the controller method is null, then an ArgumentNullException is thrown which returns the following from my HttpGlobalExceptionFilter.cs:
{
"code": 400,
"messages": [
"Value cannot be null. (Parameter 'year')"
],
"developerMessage": null
}
However, what about exceptions thrown at the controller level? For example, this is my controller method:
public async Task<ActionResult<Data>> GetDataByYearAsync([FromRoute] string DataId)
{
int dId;
DataType dType;
try
{
string[] dataParts = DataId.Split('-');
dType = (DataType)Enum.Parse(typeof(DataType), dataParts[0]);
dId = int.Parse(dataParts[1]);
}
catch (Exception ex)
{
return BadRequest();
}
Data result = await _dataService.FindData(dType, dId).ConfigureAwait(false);
if (result == null)
return NotFound();
return result;
}
If the DataId parameter is null then I get the following exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
thrown at this line:
string[] dataParts = DataId.Split('-');
This leads to the following:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-a0aaaa0aa000000aa00a00a00000a0a0-a0a000000000a000-00"
}
How should I return the error/exception at the controller level?
BadRequest()method can, depending on your .Net Core version, accept various objects (2.2, for example, can accept astringmessage). Are you able to use that to provide a more readable error message?