Skip to content

Instantly share code, notes, and snippets.

@hidegh
Created February 14, 2018 10:22
Show Gist options
  • Save hidegh/67c8f98e9e25c8bf6985e28a51bf0e92 to your computer and use it in GitHub Desktop.
Save hidegh/67c8f98e9e25c8bf6985e28a51bf0e92 to your computer and use it in GitHub Desktop.
//
// COMMON DLL
//
public interface IStatusCode
{
int? StatusCode { get; set; }
}
public static class IStatusCodeEx
{
public static T WithStatusCode<T>(this T @this, int statusCode)
where T : Exception, IStatusCode
{
@this.StatusCode = statusCode;
return @this;
}
}
public interface IMessageCode
{
string MessageCode { get; set; }
}
public static class IMessageCodeEx
{
public static T WithMessageCode<T>(this T @this, object messageCode)
where T : Exception, IMessageCode
{
@this.MessageCode = messageCode?.ToString();
return @this;
}
}
public class BaseException : Exception, IMessageCode, IStatusCode
{
public string MessageCode { get; set; }
public int? StatusCode { get; set; }
public BaseException() : base() { }
public BaseException(string message) : base (message) { }
public BaseException(string message, Exception innerException) : base(message, innerException) { }
}
//
// WEB
//
public class ExceptionFilter : IExceptionFilter
{
private ILogger logger;
public ExceptionFilter(ILogger<ExceptionFilter> logger)
{
this.logger = logger;
}
public void OnException(Microsoft.AspNetCore.Mvc.Filters.ExceptionContext context)
{
logger.LogError(0, context.Exception, context.Exception.Message);
var data = new ApiResult
{
StatusCode = (context.Exception as IStatusCode)?.StatusCode ?? (int) System.Net.HttpStatusCode.InternalServerError,
Message = context.Exception.Message,
MessageCode = (context.Exception as IMessageCode)?.MessageCode ?? "ERROR",
ExceptionType = context.Exception.GetType().FullName,
ExceptionDetails = context.Exception.ToString(),
ModelValidationResult = context.ModelState?.ToCustomValidationResult()
};
// Generic result (so it can be xml or json)
var result = new ObjectResult(data) { StatusCode = data.StatusCode };
context.Result = result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment