Exception capture in web api. Should I use a try-catch statement?

That's an example ApiController

[RequestExceptionFilter]
public class RequestController : ApiController
{
    public IHttpActionResult Post([FromBody]Request RequestDTO)
    {
        //some code over here
        throw new DTONullException(typeof(Request.Models.DTO.Request));

This is my custom exception handler

public class RequestExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        { 
            if (context.Exception is DTONullException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("DTO is null"),
                    ReasonPhrase = "DTO is null",
                };
            }

            base.OnException(context);
        }
    }

And when debugging, I get this error:

An exception of type 'Request.Controllers.DTONullException' occurred in Request.dll but was not handled in user code

enter image description here

Should I use the syntax try-catchhere? What is an agreement?

In all the samples that I see on the Internet, people are simple throw the exception, but they do not seem to catch it.

(Of course, if I click Run, the application returns BadRequestas expected, but the question is, should I use try-catchor just leave the above code as such?)

+4
source share
1 answer

ASP.NET( , WebForms/MVC/WebApi) - Application_Error global.asax.

, , , , IExceptionHandler.

class OopsExceptionHandler : ExceptionHandler
{
    public override void HandleCore(ExceptionHandlerContext context)
    {
        context.Result = new TextPlainErrorResult
        {
            Request = context.ExceptionContext.Request,
            Content = "Oops! Sorry! Something went wrong." +
                      "Please contact support@contoso.com so we can try to fix it."
        };
    }

    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = 
                             new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent(Content);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
}

webapi2 :

config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());
+3

Source: https://habr.com/ru/post/1544920/


All Articles