From 7cd2929d7c3c7c4eaecf0b3f9381bb0d2c37ea54 Mon Sep 17 00:00:00 2001 From: Sorah Fukumori Date: Thu, 30 Nov 2017 19:11:23 +0900 Subject: [PATCH 2/2] Add Exception#display to log exception [Feature #14141] --- NEWS | 1 + error.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/NEWS b/NEWS index 27467d2..e4136cd 100644 --- a/NEWS +++ b/NEWS @@ -34,6 +34,7 @@ with all sufficient information, see the ChangeLog file or Redmine * Exception * Exception#formatted [Feature #14141] + * Exception#display [Feature #14141] * Dir diff --git a/error.c b/error.c index 72e0793..c918fd6 100644 --- a/error.c +++ b/error.c @@ -938,6 +938,42 @@ exc_formatted(VALUE exc) /* * call-seq: + * exception.display(port=$stderr) -> nil + * + * Prints formatted exception on the given port (default to $stderr). + * Format includes backtrace, exception class and exception message. + * + * This method is useful to log caught exceptions. + * + * begin + * some_work + * rescue => e + * e.display + * retry + * end + */ + +static VALUE +exc_display(int argc, VALUE *argv, VALUE exc) +{ + VALUE str = rb_str_new2(""); + VALUE out; + + if (argc == 0) { + out = rb_stderr; + } + else { + rb_scan_args(argc, argv, "01", &out); + } + + rb_ec_error_write(exc, Qundef, str); + rb_io_write(out, str); + + return Qnil; +} + +/* + * call-seq: * exception.message -> string * * Returns the result of invoking exception.to_s. @@ -2199,6 +2235,7 @@ Init_Exception(void) rb_define_method(rb_eException, "==", exc_equal, 1); rb_define_method(rb_eException, "to_s", exc_to_s, 0); rb_define_method(rb_eException, "formatted", exc_formatted, 0); + rb_define_method(rb_eException, "display", exc_display, -1); rb_define_method(rb_eException, "message", exc_message, 0); rb_define_method(rb_eException, "inspect", exc_inspect, 0); -- 2.10.2