I'm coming from a Java/Spring background and I'm trying to learn .NET 5.I'm working on a Web API,everything is Ok, but somehow I couldn't understand or make it work, I've tried some solutions found online, but as things changed over years I don't know if they don't work anymore or there is some better way to do this.
Basically, I want to handle errors within my .NET API.
My service has this code :
public Users execute(int id)
{
var foundUser = this.userRepository.findById(id);
if (foundUser == null)
{
throw new HttpException(HttpStatusCode.NotFound, "User not found");
}
return foundUser;
}
HttpException is a custom Exception I made so I can possess have the control over the Status Code
using System;
using System.Net;
namespace dotnetex.shared.Errors
{
public class HttpException : Exception
{
public HttpStatusCode Status { get; set; }
public HttpException(HttpStatusCode status, string msg) : base(msg)
{
Status = status;
}
}
}
My startup class has the Exception Handler pointing to my route :
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/error"); // Add this
[...]
And my route looks like this
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace dotnetex.shared.Errors.Controller
{
[ApiController]
public class ErrorController : ControllerBase
{
[Route("/error")]
public IActionResult Error()
{
var exception = HttpContext.Features.Get<IExceptionHandlerFeature>();
HttpException error = (HttpException)exception.Error;
var statusCode = (int)error.Status;
return Problem(detail: error.Message, statusCode: statusCode);
}
}
}
For some reason, when I get the statusCode from "error" variable, I get my response broken, my Insomnia tells me Error: Transferred a partial file
. Debbuging shows me the statusCode variable is set. When I set by code a number, things works as intended.
I've tried to call the Endpoint In Insomnia,Postman,Chrome Browser,CURL. All of them show errors
In the end,If it's possible.I want to return from this route a custom error object named API Error instead of the "Problem",like this one :
namespace dotnetex.shared.Errors
{
public class APIError
{
private int status_code = 500;
private string message = "";
public APIError(int status_code, string message)
{
this.status_code = status_code;
this.message = message;
}
}
}
The exception in console is :
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
dotnetex.shared.Errors.HttpException: User not found
at dotnetex.modules.users.Services.Implementations.GetUserByIdService.GetUserByIdService.execute(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/Implementations/GetUserByIdService/GetUserByIdService.cs:line 23
at modules.users.Services.UserServices.GetUserById(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/UserServices.cs:line 45
at modules.users.Controllers.UsersControllers.getSingleUser(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Controllers/UsersControllers.cs:line 53
at lambda_method1(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
warn: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[4]
No exception handler was found, rethrowing original exception.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM6S5CSRT4C8", Request id "0HM6S5CSRT4C8:00000002": An unhandled exception was thrown by the application.
dotnetex.shared.Errors.HttpException: User not found
at dotnetex.modules.users.Services.Implementations.GetUserByIdService.GetUserByIdService.execute(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/Implementations/GetUserByIdService/GetUserByIdService.cs:line 23
at modules.users.Services.UserServices.GetUserById(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/UserServices.cs:line 45
at modules.users.Controllers.UsersControllers.getSingleUser(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Controllers/UsersControllers.cs:line 53
at lambda_method1(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
So if you can help me finding a solution please, I would be grateful.
Thank you in advance!
ASP.NET Core 5 introduced breaking-change in handling the response status code NotFound 404
. Use ExceptionHandlerOptions.AllowStatusCode404Response property.
Fix UseExceptionHandler
method like this:
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler(
new ExceptionHandlerOptions()
{
AllowStatusCode404Response = true, // important!
ExceptionHandlingPath = "/error"
}
);
}