ExceptionHandler无法捕获响应异常

时间:2019-02-13 06:50:31

标签: c# asp.net-core .net-core

我正在dotnet core上创建一个Web api应用程序,尝试捕获异常,但是它不起作用

using Microsoft.AspNetCore.Mvc;
using System;

namespace WebApplication1.Controllers
{
    public class TestModel
    {
        public long Num { get; set; }
        public decimal TotalCost { get; set; }
        public decimal Avg => Math.Round(TotalCost / Num, 4);
    }
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<TestModel> Get()
        {
            return new TestModel { Num = 0, TotalCost = 1 };
        }
    }
}

我希望输出一个异常,但它显示正常

1 个答案:

答案 0 :(得分:2)

在您调用.Avg:_ = l.Avg;之前,它不会引发异常,因此实际的代码将被触发并抛出DivideByZeroException异常。

    [HttpGet]
    public ActionResult<TestModel> Get()
    {

        var l =  new TestModel { Num = 0, TotalCost = 1 };
        _ = l.Avg;

        return l;
    }