Reputation: 10068
Is there a way I can return internal server error with the exception details?
For example if I have something like the following:
[HttpPost]
public IHttpActionResult test(MyDto dto)
{
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
//do some stuff
transaction.Commit();
return Ok();
}
catch (Exception ex)
{
transaction.Rollback();
return InternalServerError(new Exception(ex.Message));
}
}
}
Which give me the following. but as you can see there is no inner exception details to provide any meaningful information.
{
"message": "An error has occurred.",
"exceptionMessage": "An error occurred while updating the entries. See the
inner exception for details.",
"exceptionType": "System.Exception",
"stackTrace": null
}
Basically I would like some more info regarding the exception as an when it occurs so that I can troubleshoot?
Upvotes: 1
Views: 3926
Reputation: 249
The easiest way to expose the exception details is to set the configuration property IncludeErrorDetailPolicy = Always in your HttpConfiguration or. Web.conf.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/configuring-aspnet-web-api
After that, you can throw your execption and asp.net creates the InternalServerError-Response.
Another way is to create your own error object and retuns it with the information.
But you should be careful with providing to much information about your internal server information for security reasones.
public static void Register(HttpConfiguration config)
{
Logger.Info("WebApiConfig: Register: Start");
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// ...
}
[HttpPost]
public IHttpActionResult test(MyDto dto)
{
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
//do some stuff
transaction.Commit();
return Ok();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
Upvotes: 1