-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8a08b88
commit 91b71dc
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
using System.Text.Json; | ||
using System.Threading; | ||
using Microsoft.AspNetCore.Diagnostics; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace RestDesign.Services; | ||
|
||
public class RestDesignExceptionHandler : IExceptionHandler | ||
{ | ||
private readonly IHostEnvironment _environment; | ||
|
||
public RestDesignExceptionHandler(IHostEnvironment environment) | ||
{ | ||
_environment = environment; | ||
} | ||
|
||
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, | ||
Exception exception, | ||
CancellationToken cancellationToken) | ||
{ | ||
if (exception is not null) | ||
{ | ||
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; | ||
httpContext.Response.ContentType = "application/json"; | ||
|
||
// Generate the response | ||
object? error; | ||
|
||
if (_environment.IsProduction()) | ||
{ | ||
error = new | ||
{ | ||
Message = "Server Error. Please contact support.", | ||
MessageKey = "exceptionThrownServer" | ||
}; | ||
} | ||
else | ||
{ | ||
error = new | ||
{ | ||
Message = exception.Message, | ||
MessageKey = "", | ||
StackTrace = exception.StackTrace, | ||
ExceptionType = exception.GetType().Name, | ||
InnerException = exception.InnerException?.ToString() | ||
}; | ||
} | ||
|
||
await httpContext.Response.WriteAsJsonAsync(error); | ||
|
||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
} |