An exception filter (either as an attribute, or a global filter) is what you are looking for. From the docs:
Exception filters handle unhandled exceptions, including those that occur during controller creation and model binding. They are only called when an exception occurs in the pipeline. They can provide a single location to implement common error handling policies within an app.
If you want any unhandled exception to be returned as JSON, this is the simplest method:
public class JsonExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
var result = new ObjectResult(new
{
code = 500,
message = "A server error occurred.",
detailedMessage = context.Exception.Message
});
result.StatusCode = 500;
context.Result = result;
}
}
You can customize the response to add as much detail as you want. The ObjectResult will be serialized to JSON.
Add the filter as a global filter for MVC in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(JsonExceptionFilter));
});
}