Exception handling in Web API

后端 未结 3 1114
没有蜡笔的小新
没有蜡笔的小新 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: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 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.

提交回复
热议问题