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
.
¿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) } }
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 .