locked
asp.net core web api response object wrapper RRS feed

  • Question

  • User1838940990 posted

    Hi All,

    hope you are doing great.

    We  have a web api which developed internally  which is  used internally at the moment  , but  later it will be used by one or more tow external clients shortly.

    W have front in reactjs which consumes this api, here we are facing some in consistency in the  response object while we return error response or success from the controller end points.

    Currently the response is like below

    [Authorize]
            [HttpPost]
            [Route("Get")]
            public IActionResult GetOrder(Order order)
            {
                
                try
                {
          
                   var  orderDetails = orderRepository.GetOrderDetails(order);
                    return Ok(orderDetails);
                }
                catch (Exception ex)
                {
                    _logger.LogError("Exception occured in GetOrder {0} ", ex.GetBaseException().Message);
                    return StatusCode(StatusCodes.Status500InternalServerError, ex.GetBaseException().Message);
                }
                
            }

    is it a best practice to create a wrapper to return object consistently while returning error or success , so that the front don't need to write any magic code to handle different type of response , os that it can expect a standard object irrespective of error or success.

    Below are the objects template I can see in forums 

    		
    	public class ApiResponse
        {
            public HttpStatusCode StatusCode { get; set; }
            public string ErrorMessage { get; set; }
            public object Result { get; set; }
            public DateTime Timestamp { get; set; }
            public long? Size { get; set; }
        }

    can you  help me to get insight on this,  is  there any best practice followed in public facing enterprise api.

    thanks,

    Monday, April 5, 2021 8:36 AM

Answers

  • User-474980206 posted

    I prefer returning a failed status code rather than success with an error indicator Igor most errors. As the client code still need to handle failed for network errors, it just makes sense to do all error handling in the same place.

    But if it’s a form post and the form data fails validation, then the api response makes sense because this is a user correctable error, and an expected response.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 5, 2021 2:36 PM
  • User1120430333 posted

    I don't see why you need any try/catch in the Core WebAPI.

    How to Catch All Exceptions in C# & Find All Application Errors – Stackify

    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Configuration;
    using Serilog;
    
    namespace WebAPI
    {
        public class ErrorHandlingFilter : ExceptionFilterAttribute
        {
            private readonly IConfiguration _configuration;
    
            public ErrorHandlingFilter(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public override void OnException(ExceptionContext context)
            {
                var log = new LoggerConfiguration().ReadFrom.Configuration(_configuration).CreateLogger();
    
                var exception = context.Exception;
    
                if (exception.InnerException != null)
                {
                    log.Error("Message = " + exception.Message + " Inner.Exception.Message = " +
                              exception.InnerException.Message
                              + " Stack Trace = " + exception.StackTrace);
                }
                else
                {
                    log.Error("Message = " + exception.Message + " Stack Trace = " + exception.StackTrace);
                }
    
                context.ExceptionHandled = false; //optional 
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 5, 2021 2:57 PM

All replies

  • User-474980206 posted

    I prefer returning a failed status code rather than success with an error indicator Igor most errors. As the client code still need to handle failed for network errors, it just makes sense to do all error handling in the same place.

    But if it’s a form post and the form data fails validation, then the api response makes sense because this is a user correctable error, and an expected response.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 5, 2021 2:36 PM
  • User1120430333 posted

    I don't see why you need any try/catch in the Core WebAPI.

    How to Catch All Exceptions in C# & Find All Application Errors – Stackify

    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Configuration;
    using Serilog;
    
    namespace WebAPI
    {
        public class ErrorHandlingFilter : ExceptionFilterAttribute
        {
            private readonly IConfiguration _configuration;
    
            public ErrorHandlingFilter(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public override void OnException(ExceptionContext context)
            {
                var log = new LoggerConfiguration().ReadFrom.Configuration(_configuration).CreateLogger();
    
                var exception = context.Exception;
    
                if (exception.InnerException != null)
                {
                    log.Error("Message = " + exception.Message + " Inner.Exception.Message = " +
                              exception.InnerException.Message
                              + " Stack Trace = " + exception.StackTrace);
                }
                else
                {
                    log.Error("Message = " + exception.Message + " Stack Trace = " + exception.StackTrace);
                }
    
                context.ExceptionHandled = false; //optional 
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 5, 2021 2:57 PM