I have multiple .Net controllers that look like:
[HttpGet("{id}")]
public async Task<ActionResult<Int32>> GetById(Int32 id)
{
id = FormatId(id);
return lookupId(id);
}
Assume I have dozens of these endpoints in multiple controllers and some of them require the id to be formatted a certain way like an integer padded to 5 digits, so the FormatId pads it for me and if it’s more than 5 digits, it throws a BadHttpRequestException.
Now instead of littering all of the id related endpoints with:
try/catch { return BadRequest() }
Is there anyway I can attach a common exception handler to any/all endpoints/controllers?
Basically I just want to do something like:
Controller.OnException(Exception e)
{
if (e.Type == BadHttpRequestException) // Ignore invalid C# syntax, just pseudocode
{
return BadRequest(e.Message);
}
}
I assume that would be the supported way, or can I have access to the layer above the controller’s endpoint such that I could catch it myself and do something like:
public MyWrapperEndpoint(T endpoint)
{
try {
endpoint(); // call whatever endpoint was requested (GetById)
} catch (BadHttpRequestException e) {
return BadRequest(e.Message); // Return the common exception message
}
}