将自定义异常从注入的服务抛出到控制器

Throwing custom exceptions from injected service to controller

这应该是一个很简单的问题,但我似乎找不到答案。

我正在使用标准依赖项注入将自定义服务注入 NET Core Web 中的控制器 API。

private readonly IMyService _myService;
public MyController(IMyService MyService)
{
    _myService= MyService;
}

IMyService 包含所有具有逻辑的方法,MyService 实现了它。 现在,是否可以通过接口向控制器公开自定义异常类型,这样我就可以从 MyService 中抛出这些异常并在 MyController 中捕获它们?据我了解 C# - 接口不能将自定义 类 作为属性。 或者这种方法完全错误?我还应该如何正确地将不同类型的错误从服务传回控制器?

是的,你可以!

示例:

假设您有这个自定义异常

using System;
using System.Runtime.Serialization;

namespace SO.DI._001.Exceptions
{
    public class SomeCustomException : Exception
    {
        public SomeCustomException()
        {
        }

        public SomeCustomException(string message) : base(message)
        {
        }

        public SomeCustomException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected SomeCustomException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}

假设您的服务是

using SO.DI._001.Exceptions;

namespace SO.DI._001.Services
{
    public class MyService : IMyService
    {
        public void DoSomething()
        {
            throw new SomeCustomException();
        }
    }
}

所以,你的控制器可以是这样的:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SO.DI._001.Exceptions;
using SO.DI._001.Services;
using System;

namespace SO.DI._001.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IMyService _myService;

        public WeatherForecastController(ILogger<WeatherForecastController> logger,
                                         IMyService myService)
        {
            _logger = logger;
            _myService = myService;
        }

        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                _myService.DoSomething();
            }
            catch (SomeCustomException ex)
            {
                _logger.LogError($"{nameof(SomeCustomException)} {ex.Message}");

                //Handle it
            }
            catch (AnotherCustomerException ex) when (ex.Message == "blabla")
            {
                _logger.LogError($"{nameof(AnotherCustomerException)} {ex.Message} blablabla");

                //Handle it
            }
            catch (AnotherCustomerException ex)
            {
                _logger.LogError($"{nameof(AnotherCustomerException)} {ex.Message}");

                //Handle it
                //Handle it
            }
            catch (Exception ex)
            {
                //This is the default exception
            }


            return Ok();
        }
    }
}