Juanito Fatas
Juanito Fatas

Reputation: 9949

How to manually create exception with message and backtrace

How can I create an exception with backtrace?

I know we could do something like this to achieve this:

begin
  raise StandardError, "message"
rescue StandardError => exception
  exception.backtrace
end

Or

exception = StandardError.new("message")
exception.set_backtrace(caller)

But I am looking for something like this:

exception = StandardError.new("message", backtrace: caller)

Is there a way that I can initialize an exception with customized message and backtrace?

Upvotes: 25

Views: 7636

Answers (4)

siannopollo
siannopollo

Reputation: 1466

Along the lines of the other answers, you will need to use set_backtrace on the error object. But you can do this in the initialize method of a custom error like so:

class MyError < StandardError
  def initialize(message, backtrace)
    super(message)
    set_backtrace backtrace
  end
end

This way you can encapsulate all your logic in a single class without needing an error factory.

Upvotes: 4

Juanito Fatas
Juanito Fatas

Reputation: 9949

Wrap in an functional class by yourself:

class ErrorCreator
  def self.new(error, message = nil, backtrace: caller)
    exception = error.new(message)
    exception.set_backtrace(backtrace)
    exception
  end
end

Use:

ErrorCreator.new(StandardError, "failed")
ErrorCreator.new(StandardError, "failed", backtrace: caller)

I created a gem for anyone to use: https://github.com/JuanitoFatas/active_error.

Upvotes: 6

XavM
XavM

Reputation: 873

You can create your own exceptions like this :

Create a file in app > exceptions > name_exception.rb

name_exception.rb

class NameException < StandardError
  def initialize(message, backtrace)
    super
    backtrace
  end
end

Then in your file

raise NameException.new(message, backtrace)

You can adapt it to your needs but the pattern is here.

Upvotes: 2

sawa
sawa

Reputation: 168071

You can't initialize an exception with a backtrace, but you can assign one right after initialization.

exception = StandardError.new("message")
exception.set_backtrace(caller)

Upvotes: 36

Related Questions