How to change the status code and response based on type of exception

I love Sentry!

This is a question and it might be due to lack of knowledge but also related if it can be done using Sentry or just somehow capturing if an error happened in a custom middleware.

I want when a specific type of exception happens Sentry to do all the magic as usual but then another middleware to set the status code and response body.

For example let’s say a DomainException occurred and I want to do the below.

context.Response.StatusCode = StatusCodes.Status400BadRequest;
context.Response.ContentType = MediaTypeNames.Application.Json;
var responseDto = new ErrorResponseDto(ex.Message);
var responseJson = JsonConvert.SerializeObject(responseDto, _jsonSettings);
await context.Response.WriteAsync(responseJson);

Thanks!

You don’t say what framework you’re using - looks like C#. If you’re using ASP .NET Core, you can handle this in custom Middleware. There are plenty of examples on using middleware for exception handling. Here is one that I found helpful - https://code-maze.com/global-error-handling-aspnetcore/

You have to be very careful though about trying to write to the Response or change status code if the Response has already started to begin writing - see https://www.strathweb.com/2018/07/overriding-externally-set-headers-and-http-status-codes-in-asp-net-core/

Hope this helps.