首页 > 其他分享 >265 Custom Exceptions(更容易定位报错内容具体是什么)

265 Custom Exceptions(更容易定位报错内容具体是什么)

时间:2024-06-07 19:01:11浏览次数:13  
标签:InvalidPersonIdException Custom 报错 265 Exceptions ArgumentException message publ

优势

Custom Exceptions相比于ArgumentException/ArgumentNullException,更容易定位报错内容具体是什么,报错内容与具体业务相关。

示例

新建类库项目Exceptions,为Services/CRUDExample项目添加Exceptions项目引用

Exceptions项目中添加InvalidPersonIdException.cs

namespace Exceptions
{
    public class InvalidPersonIdException : ArgumentException
    {
        public InvalidPersonIdException() : base()
        {

        }

        public InvalidPersonIdException(string? message) : base(message)
        {

        }

        public InvalidPersonIdException(string? message, Exception? innerException) : base(message, innerException)
        {

        }
    }
}

PersonsService.cs中UpdatePerson方法中使用自定义的InvalidPersonIdException替换掉ArgumentException

if (matchingPerson == null)
{
    //throw new ArgumentException("Given person id doesn't exist");
    throw new InvalidPersonIdException("Given person id doesn't exist");
}

测试

PersonsController.cs中HttpPost Edit方法中在updatePerson前面添加一段代码

if (ModelState.IsValid)
{
    personUpdateRequest.PersonId = Guid.NewGuid();//测试InvalidPersonIdException添加
    PersonResponse updatedPerson = await _personsService.UpdatePerson(personUpdateRequest);
    return RedirectToAction("Index");
}

拓展阅读

Best practices for exceptions - .NET | Microsoft Learn

Gitee获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

标签:InvalidPersonIdException,Custom,报错,265,Exceptions,ArgumentException,message,publ
From: https://blog.csdn.net/KevinHuang2088/article/details/139534000

相关文章