Exception handling in Web API

后端 未结 3 1117
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 08:54

In my Web API project, I created sub projects (class libraries) where I handle actual data handling operations. My backend database is DocumentDB.

My question is how

相关标签:
3条回答
  • 2021-01-12 09:08

    The error handling depends on your logic and how your API respond to its consumers.

    Basically, you have to use HTTP Status Codes according to the type of error.

    In your data access and business layer methods, you can depend on the return type. For example, in all methods that queries the database, if the object is not there, you can return NULL, and in your web API, if the method returns NULL, then simply return NotFound() which will respond to the client with a 404.

    As for the exceptions:

    You can use Error Codes in your business and data access layer and check for these codes in your web API actions. Then return a suitable status code accordingly. Ex: return a status code of 500 if there has been a connection issue to the database, or return a 400 (Bad Request) if the user didn't provide all required action parameters in the correct format.

    In case of any other exception that you didn't catch, you can go with the global exception handler described by @Win

    0 讨论(0)
  • 2021-01-12 09:11

    If you want to intercept and log the error in your console application but still forward the error to the caller, just use throw; at the end of your catch statement in your console application.

    It will rethrow the same exception to the caller, so your application can be aware of the exception in the "callee" as well as in the "caller".

    0 讨论(0)
  • 2021-01-12 09:19

    ASP.NET Web API 2.1 have framework support for global handling of unhandled exceptions.

    It allows use to customize the HTTP response that is sent when an unhandled application exception occurs.

    So, do not catch exception in Class Library. If you are required to log exception in Class Library, then re-throw those exception to Presentation.

    WebApiConfig

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // ...
    
            config.Services.Replace(typeof (IExceptionHandler), 
                new GlobalExceptionHandler());
        }
    }
    

    GlobalExceptionHandler

    public class GlobalExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            var exception = context.Exception;
    
            var httpException = exception as HttpException;
            if (httpException != null)
            {
                context.Result = new CustomErrorResult(context.Request,
                    (HttpStatusCode) httpException.GetHttpCode(), 
                     httpException.Message);
                return;
            }
    
            // Return HttpStatusCode for other types of exception.
    
            context.Result = new CustomErrorResult(context.Request, 
                HttpStatusCode.InternalServerError,
                exception.Message);
        }
    }
    

    CustomErrorResult

    public class CustomErrorResult : IHttpActionResult
    {
        private readonly string _errorMessage;
        private readonly HttpRequestMessage _requestMessage;
        private readonly HttpStatusCode _statusCode;
    
        public CustomErrorResult(HttpRequestMessage requestMessage, 
           HttpStatusCode statusCode, string errorMessage)
        {
            _requestMessage = requestMessage;
            _statusCode = statusCode;
            _errorMessage = errorMessage;
        }
    
        public Task<HttpResponseMessage> ExecuteAsync(
           CancellationToken cancellationToken)
        {
            return Task.FromResult(_requestMessage.CreateErrorResponse(
                _statusCode, _errorMessage));
        }
    }
    

    Credit to ASP.NET Web API 2: Building a REST Service from Start to Finish, and source code.

    0 讨论(0)
提交回复
热议问题