Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
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 .

about 4 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) } }
about 4 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 .

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!