public int GetErrorCode(BaseApiException exception) { try { var exceptionType = exception.GetType(); if (!_map.ContainsKey(exceptionType)) { throw new ArgumentException( $"Exception {exceptionType.FullName} has not been mapped accordingly. Should be treated as an unexpected exception"); } var exceptionDescriptionType = typeof(ExceptionDescription <>).MakeGenericType(exceptionType); var instance = Convert.ChangeType(_map[exceptionType], exceptionDescriptionType); var property = exceptionDescriptionType.GetProperty("ErrorCode"); var method = property?.PropertyType.GetMethod("Invoke"); var errorCode = method?.Invoke(property.GetValue(instance), new object[] { exception }); if (errorCode == null) { throw new ArgumentException( $"Exception {exceptionType.FullName} has not been mapped accordingly. Should be treated as an unexpected exception"); } return((int)errorCode); } catch { throw new ArgumentException( $"Exception {exception.GetType().FullName} has not been mapped accordingly. Should be treated as an unexpected exception"); } }
public HttpStatusCode GetExceptionHandlerReturnCode(BaseApiException exception) { var exceptionType = exception.GetType(); if (!exceptionType.IsSubclassOf(typeof(BaseApiException))) { throw new ArgumentException("exception needs to be a subclass of BaseApiException"); } if (!_map.ContainsKey(exceptionType)) { throw new ArgumentException($"Exception {exceptionType.FullName} has not been mapped. Should be treated as an unexpected exception"); } return(_map[exceptionType].ExceptionHandlerReturnCode); }
public override void OnException(ExceptionContext context) { var baseException = context.Exception.GetBaseException(); int statusCode = StatusCodes.Status500InternalServerError; BaseApiException baseApiException = null; if (baseException is BaseApiException) { baseApiException = ((BaseApiException)baseException); statusCode = baseApiException.ResponseHttpStatusCode; } context.HttpContext.Response.StatusCode = statusCode; context.Result = new JsonResult(new { StatusCode = statusCode, error = baseException.Message, error_description = baseApiException?.BackEndMessage }); base.OnException(context); }