# ASP.Net7 Exception Attribute
###### tags: `C#`
## 定義自己的 exception
```csharp
using System;
public class TestException : Exception
{
public TestException()
{
}
public TestException(string message)
: base(message)
{
}
public TestException(string message, Exception inner)
: base(message, inner)
{
}
}
```
#### 相關連結
[如何建立使用者定義的例外狀況](https://learn.microsoft.com/zh-tw/dotnet/standard/exceptions/how-to-create-user-defined-exceptions)
## 定義自己的 exception attribute
1. 定義自己的 exception attribute,繼承 `IActionFilter`,接著實作 `OnException()`
可以判斷不同的 exception 做不同的事
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public class TestExceptionAttribute : IExceptionFilter
{
private readonly ILogger<TestExceptionAttribute> _logger;
public TestExceptionAttribute(ILogger<TestExceptionAttribute> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
object result = null;
//統一回傳的格式
if (context.Exception is UserException)
{
var gameConnectException = (UserException)context.Exception;
result = new
{
status = 500,
msg = $"code:{gameConnectException.ErrorCode.ToString("D")}",
desc = gameConnectException.Message
};
}
else
{
result = new
{
status = 500,
desc = context.Exception.Message
};
}
_logger.LogError(context.Exception.ToString());
context.Result = new OkObjectResult(result);
}
}
```
2. 註冊 attribute 在 `Startup.cs ConfigureServices()`
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MovieContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("sqlConString")));
services.AddScoped<TestExceptionAttribute>();
services.AddControllers();
}
```
3. 在 service 使用 attribute。可依 method 或直接掛在 controller 上,要記得 DI 註冊
```csharp
[HttpPost]
[ServiceFilter(typeof(TestExceptionAttribute))]
public IActionResult Post([FromBody] Movie movie)
{
_context.Movies.Add(movie);
_context.SaveChanges();
return CreatedAtRoute("MovieById", new { id = movie.Id }, movie);
}
```
### 相關連結
[Implementing Action Filters in ASP.NET Core (.net7)](https://code-maze.com/action-filters-aspnetcore/)
[ASP.NET Core 2 系列 - Filters](https://ithelp.ithome.com.tw/articles/10195407)
[ASP.NET Web API Exception Filter](https://www.huanlintalk.com/2013/01/aspnet-web-api-exception-filter.html)