From 49d722c16f25706c0469dd437a19ec0f84dbbe2a Mon Sep 17 00:00:00 2001 From: Chris Hobbs Date: Sat, 31 Mar 2018 19:30:54 +0100 Subject: [PATCH] Print exception cause when inspecting with backtrace (#5833) --- spec/std/exception_spec.cr | 16 ++++++++++++++++ src/exception.cr | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/spec/std/exception_spec.cr b/spec/std/exception_spec.cr index d75e71ee2368..8a04449ea727 100644 --- a/spec/std/exception_spec.cr +++ b/spec/std/exception_spec.cr @@ -18,4 +18,20 @@ describe "Exception" do ex = FooError.new("foo?") ex.inspect.should eq("#") end + + it "inspects with cause" do + cause = Exception.new("inner") + ex = expect_raises(Exception, "wrapper") do + begin + raise cause + rescue ex + raise Exception.new("wrapper", cause: ex) + end + end + + ex.cause.should be(cause) + ex.inspect_with_backtrace.should contain("wrapper") + ex.inspect_with_backtrace.should contain("Caused by") + ex.inspect_with_backtrace.should contain("inner") + end end diff --git a/src/exception.cr b/src/exception.cr index 5bb82b13510a..f3a241fa1bd8 100644 --- a/src/exception.cr +++ b/src/exception.cr @@ -59,6 +59,12 @@ class Exception io.print " from " io.puts frame end + + if cause = @cause + io << "Caused by: " + cause.inspect_with_backtrace(io) + end + io.flush end end