• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

236
Views
¿Cómo puedo lanzar una excepción en un controlador ASP.NET Core WebAPI que devuelve un objeto?

En Framework WebAPI 2, tengo un controlador que se ve así:

 [Route("create-license/{licenseKey}")] public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license) { try { // ... controller-y stuff return await _service.DoSomethingAsync(license).ConfigureAwait(false); } catch (Exception e) { _logger.Error(e); const string msg = "Unable to PUT license creation request"; throw new HttpResponseException(HttpStatusCode.InternalServerError, msg); } }

Efectivamente, recibo un error 500 con el mensaje.

¿Cómo puedo hacer algo similar en ASP.NET Core Web API?

HttpRequestException no parece existir. Preferiría continuar devolviendo el objeto en lugar de HttpRequestMessage .

over 3 years ago · Santiago Trujillo
2 answers
Answer question

0

¿Qué tal algo como esto? Cree un middleware donde expondrá ciertos mensajes de excepción:

 public class ExceptionMiddleware { private readonly RequestDelegate _next; public ExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; if (ex is ApplicationException) { await context.Response.WriteAsync(ex.Message); } } } }

Úsalo en tu aplicación:

 app.UseMiddleware<ExceptionMiddleware>(); app.UseMvc();

Y luego en tu acción lanza la excepción:

 [Route("create-license/{licenseKey}")] public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license) { try { // ... controller-y stuff return await _service.DoSomethingAsync(license).ConfigureAwait(false); } catch (Exception e) { _logger.Error(e); const string msg = "Unable to PUT license creation request"; throw new ApplicationException(msg); } }

Un mejor enfoque es devolver un IActionResult . De esa manera no tienes que lanzar una excepción. Como esto:

 [Route("create-license/{licenseKey}")] public async Task<IActionResult> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license) { try { // ... controller-y stuff return Ok(await _service.DoSomethingAsync(license).ConfigureAwait(false)); } catch (Exception e) { _logger.Error(e); const string msg = "Unable to PUT license creation request"; return StatusCode((int)HttpStatusCode.InternalServerError, msg) } }
over 3 years ago · Santiago Trujillo Report

0

Es mejor no capturar todas las excepciones en cada acción. Simplemente detecte las excepciones que necesita para reaccionar específicamente y capture (y ajuste a HttpResponse) todo el resto en Middleware .

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error