Skip to content

Commit ca569fb

Browse files
committed
refactor(jsonapi-exception-filter): use exception factory
1 parent 5edc932 commit ca569fb

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.Linq;
3+
4+
namespace JsonApiDotNetCore.Internal
5+
{
6+
public static class JsonApiExceptionFactory
7+
{
8+
public static JsonApiException GetException(Exception exception)
9+
{
10+
var exceptionType = exception.GetType().ToString().Split('.').Last();
11+
switch(exceptionType)
12+
{
13+
case "JsonApiException":
14+
return (JsonApiException)exception;
15+
case "InvalidCastException":
16+
return new JsonApiException("409", exception.Message);
17+
default:
18+
return new JsonApiException("500", exception.Message);
19+
}
20+
}
21+
}
22+
}

src/JsonApiDotNetCore/Middleware/JsonApiExceptionFilter.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,8 @@ public void OnException(ExceptionContext context)
1919
{
2020
_logger?.LogError(new EventId(), context.Exception, "An unhandled exception occurred during the request");
2121

22-
var jsonApiException = context.Exception as JsonApiException;
22+
var jsonApiException = JsonApiExceptionFactory.GetException(context.Exception);
2323

24-
if(jsonApiException == null)
25-
jsonApiException = new JsonApiException("500", context.Exception.Message);
26-
2724
var error = jsonApiException.GetError();
2825
var result = new ObjectResult(error);
2926
result.StatusCode = Convert.ToInt16(error.Status);

0 commit comments

Comments
 (0)