/
ApiExceptionFilter.cs
75 lines (64 loc) · 2.73 KB
/
ApiExceptionFilter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using MyWarehouse.Application.Common.Exceptions;
using System;
namespace MyWarehouse.WebApi.ErrorHandling
{
/// <summary>
/// Maps exceptions occurred in lower layers into HTTP responses with appropriate HTTP code.
/// Make sure to register this filter globally.
/// </summary>
public class ApiExceptionFilter : ExceptionFilterAttribute
{
private readonly ILogger<ApiExceptionFilter> _logger;
public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
//TODO: Push logging deeper, into Application layer, and dedicate this component to response mapping.
_logger.LogError($"Exception: [{context.Exception.Message}]\r\n\r\nStack Trace:\r\n{context.Exception.StackTrace}");
context.Result = ExecuteHandler(context.Exception);
context.ExceptionHandled = true;
base.OnException(context);
}
private static IActionResult ExecuteHandler(Exception exception)
=> exception switch
{
InputValidationException e => HandleValidationException(e),
EntityNotFoundException e => HandleNotFoundException(e),
_ => HandleUnknownException(exception)
};
private static IActionResult HandleUnknownException(Exception _)
{
var details = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An error occurred while processing your request.",
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1"
};
return new ObjectResult(details) { StatusCode = StatusCodes.Status500InternalServerError };
}
private static IActionResult HandleValidationException(InputValidationException exception)
{
var details = new ValidationProblemDetails(exception.Errors)
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
return new BadRequestObjectResult(details);
}
private static IActionResult HandleNotFoundException(EntityNotFoundException exception)
{
var details = new ProblemDetails()
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
Title = "The specified resource was not found.",
Detail = exception.Message
};
return new NotFoundObjectResult(details);
}
}
}