Error Handling
- Introduction
- Complete Example: Known HTTP Failure
- Configuration
- Handling Exceptions
- HTTP Exceptions
- Outside of Requests
Introduction
DotBlaze handles exceptions in one place, like Laravel. An exception thrown while handling a request is reported (logged, or sent to a service such as Sentry) and then rendered as an error response. You decide how both happen through the Exceptions class, usually in your AppServiceProvider.
Configuration
The debug option in config/App.cs controls how much the browser sees about an error. It is on by default in the Development and Testing environments and off in every other environment, so production needs nothing:
debug = false,- Debug on: the DotBlaze developer exception page handles HTML errors, including an unmatched URL or an HTTP exception. Select a stack frame to inspect its source and highlighted line, or expand library frames to trace a call into a dependency. Source excerpts require debug symbols and a matching file in the application's content root. The page includes request and runtime details, light/dark/system themes, and a Copy as Markdown action. For unhandled exceptions when the client requests a format other than HTML, ASP.NET Core supplies the developer exception response.
- Debug off: HTTP errors use custom error views or a built-in page. An unhandled exception displays
500 | Server Errorby default, or{ "message": "Server Error" }for JSON requests. The details only go to the logs.
WARNING
Never turn debug on in production: the developer exception page shows your code, configuration values, and stack traces to anyone.
Handling Exceptions
Reporting Exceptions
Reporting means logging the exception or sending it to an external service. By default every exception is logged at the Error level through logging. To also send exceptions of one type somewhere else, register a callback with Exceptions.Report in a provider's Boot method:
using DotBlaze;
public class AppServiceProvider : Provider
{
public override void Boot(WebApplication app)
{
Exceptions.Report<InvalidOrderException>(e =>
{
// ...
});
}
}The type parameter decides which exceptions the callback receives; Exceptions.Report<Exception>(...) receives all of them. Callbacks may be async:
Exceptions.Report<Exception>(async e => await Sentry.CaptureAsync(e));The exception is still logged after the callbacks run. Add .Stop() to log it only through your callback:
Exceptions.Report<InvalidOrderException>(e =>
{
// ...
}).Stop();If a callback throws (for example, the error service is down), DotBlaze logs that failure and still logs the original exception.
Global Log Context
DotBlaze adds the logged-in user's id to every exception's log entry as userId, in the logging scope. Add your own values with Exceptions.Context:
Exceptions.Context(() => new Dictionary<string, object?>
{
["tenant"] = Tenant.Current?.Id,
});The values appear in log providers that include scopes, such as the JSON console formatter, Serilog, or OpenTelemetry.
Exception Log Context
An exception can add its own values by implementing IExceptionContext:
public class InvalidOrderException(long orderId) : Exception("The order is invalid."), IExceptionContext
{
public IDictionary<string, object?> Context() => new Dictionary<string, object?> { ["order_id"] = orderId };
}The Report Helper
Sometimes you want to report an exception and carry on. The Report function sends it through your report callbacks and the log without rendering an error page:
try
{
await Payments.Charge(order);
}
catch (PaymentException e)
{
await Report(e);
return Back().With("status", "The payment failed. Please try again.");
}Rescue runs a callback, reports any exception it throws, and returns a fallback value instead:
var rate = await Rescue(() => ExchangeRates.Fetch("EUR"), fallback: 1.0m);
var size = Rescue(() => new FileInfo(path).Length, fallback: 0L, report: false);Report and Rescue come from DotBlaze.Support.Functions, which the template imports with using static. Exceptions.Report(e) does the same as Report(e).
Exception Log Levels
Exceptions are logged at the Error level. To log one type at another level:
Exceptions.Level<TimeoutException>(LogLevel.Warning);Ignoring Exceptions by Type
Exceptions that are part of normal operation can be left out of the logs. They still render their error response:
Exceptions.DontReport<CouponExpiredException>();
Exceptions.DontReport(typeof(CartEmptyException), typeof(OutOfStockException));Like Laravel, DotBlaze never reports these exceptions, because they are expected:
HttpException, includingAbort(...),ModelNotFoundException, fromFindOrFail,AuthorizationException, fromGate.Authorize,BadHttpRequestException, for example a request body that is too large.
To log one of them anyway, use StopIgnoring:
Exceptions.StopIgnoring<HttpException>();A request the client cancelled (closed tab, timeout) is not reported either.
Mapping Exceptions
Map turns one exception into another before it is reported and rendered. This is useful for exceptions from libraries:
Exceptions.Map<Stripe.StripeException>(e => new PaymentException(e.Message, e));Rendering Exceptions
Exceptions.Render replaces the error response for one type of exception. The callback gets the exception and the HttpContext, and returns an IResult:
Exceptions.Render<InvalidOrderException>((e, request) =>
Exceptions.View("errors/invalid-order", e, status: 500));
Exceptions.Render<PaymentException>((e, request) =>
Results.Json(new { message = e.Message, code = "payment_failed" }, statusCode: 402));Return null to use the default response, for example to customize only API requests:
Exceptions.Render<ModelNotFoundException>((e, request) =>
request.Request.Path.StartsWithSegments("/api")
? Results.Json(new { message = "Record not found." }, statusCode: 404)
: null);Render callbacks also run in debug mode, so you see the same response in development as in production.
By default the error response is JSON when the request accepts JSON (Accept: application/json, or an XMLHttpRequest). To decide yourself:
Exceptions.ShouldRenderJsonWhen((request, e) =>
request.Request.Path.StartsWithSegments("/api") || request.Request.WantsJson());Reportable and Renderable Exceptions
An exception can also report and render itself:
IReportableException.Report()reports the exception. Returntrueif it has been handled, orfalseto log it as usual too.IRenderableException.Render(context)builds the response. Returnnullfor the default response.
public class InvalidOrderException : Exception, IReportableException, IRenderableException
{
public async Task<bool> Report()
{
await Slack.Notify("#orders", Message);
return false; // also log it
}
public Task<IResult?> Render(HttpContext context) =>
Task.FromResult<IResult?>(Exceptions.View("errors/invalid-order", this, status: 500));
}HTTP Exceptions
Some exceptions describe an HTTP error, such as "page not found" (404) or "unauthorized" (401). Use Abort to stop a request with one, from anywhere: controllers, middleware, services:
Abort(404);
Abort(403, "You may not edit this post.");
Abort(503, headers: new Dictionary<string, string> { ["Retry-After"] = "120" });
AbortIf(!post.Published, 404);
AbortUnless(user.IsAdmin, 403);Abort throws an HttpException, which you can also throw or subclass yourself:
throw new HttpException(409, "The order was already paid.");DotBlaze turns these exceptions into HTTP errors too:
| Exception | Response |
|---|---|
ModelNotFoundException (FindOrFail, FirstOrFail) | 404 Not Found |
AuthorizationException (Gate.Authorize, Authorize in a controller) | 403 with the exception's message |
BadHttpRequestException (malformed or too large request) | its status, usually 400 or 413 |
The CSRF check (419) and the throttle middleware (429) use the same error pages. So does any response that ends with an error status and no body, such as a URL that matches no route, or return NotFound() in a controller.
For JSON requests the response is { "message": "..." }. For a 500 error the message is always Server Error, so exception details never reach the client.
Custom HTTP Error Pages
To customize the page for a status when debug is off, create resources/views/errors/{status}, as a Blade (404.blade.html) or Razor (404.cshtml) view. Its model is the HttpException:
{{-- resources/views/errors/404.blade.html --}}
@model HttpException
@extends('layouts.app')
@section('title', 'Not Found')
@section('content')
<h1>{{ Model.StatusCode }} | Page not found</h1>
<p>{{ Model.Message }}</p>
@endsectionThe application template includes an errors/404 view. If there is no view for the exact status, DotBlaze looks for errors/4xx or errors/5xx, then falls back to a built-in page. For a 500 error the model is an HttpException with the message Server Error; the original exception is in Model.InnerException.
Error views are rendered without _ViewStart.cshtml, like mail views. A Blade error view picks its layout with @extends; a Razor error view sets Layout itself. If the error view itself throws, DotBlaze logs that error and shows the built-in page.
Outside of Requests
Exceptions outside of requests go through the same reporting: report callbacks, DontReport, Level, Map, and the log context.
- Queued jobs: each failed attempt is reported. A failure that will be retried is logged as a warning, and the final failure at the exception's level (
Errorby default). See Queues. - Scheduled tasks: a failing task is reported and the other tasks keep running. See Task Scheduling.
Complete Example: Known HTTP Failure
Create this controller in the Blog template:
// app/Http/Controllers/ErrorDemoController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers;
public class ErrorDemoController : BaseController
{
public IActionResult Show() =>
throw new HttpException(409, "The example operation is already complete.");
}Add Route.Get<Blog.Controllers.ErrorDemoController>("/error-demo", c => c.Show); inside Web.Map(). Run dotblaze serve; a browser receives a 409 error page, while a request with Accept: application/json receives:
{"message":"The example operation is already complete."}The status remains 409 in both cases. For unexpected errors in production, set app__debug=false and use a generic client message while retaining server-side reporting. Custom error views must not render Model.InnerException; the complete blog test demonstrates expected 403, 404, 419, and validation failures without converting them into successful responses.