CatchBuilder¶
Compose catch clauses for try-catch statements in BodyBuilder.
See also: BodyBuilder | Emit Overview
Factory Methods¶
| Method | Description |
|---|---|
Empty() |
Create an empty catch builder |
Catch Clauses¶
| Method | Description |
|---|---|
Catch(TypeRef type, string name, configure) |
Catch a typed exception with a variable |
Catch(TypeRef type, configure) |
Catch a typed exception without a variable |
CatchAll(configure) |
Bare catch clause — catches all exceptions |
CatchWhen(TypeRef type, string name, ExpressionRef when, configure) |
Catch with a when filter |
Each configure callback receives a BodyBuilder and returns the catch block body.
Example¶
body.AddTryCatch(
tryBody => tryBody.AddStatement("await DoWork()"),
catches => catches
.Catch("OperationCanceledException", cb => cb
.AddComment("Graceful shutdown")
.AddReturn())
.Catch("Exception", "ex", cb => cb
.AddStatement("""_logger.LogError(ex, "Error")""")))
// With when filter
body.AddTryCatch(
tryBody => tryBody.AddStatement("await ProcessAsync()"),
catches => catches
.CatchWhen("HttpRequestException", "ex", "ex.StatusCode == 429", cb => cb
.AddStatement("await Task.Delay(1000)")
.AddStatement("await RetryAsync()"))
.CatchAll(cb => cb
.AddStatement("throw")))
// Try-catch-finally
body.AddTryCatchFinally(
tryBody => tryBody.AddStatement("connection.Open()"),
catches => catches.Catch("Exception", "ex", cb => cb
.AddStatement("logger.LogError(ex, \"Connection error\")")),
finallyBody => finallyBody.AddStatement("connection.Close()"))