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?
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
This blog is part of our Ruby 2.5 series. Stack trace or backtrace is a sequential representation of the stack of method calls in a program which gets printed when an exception is raised. It is often used to find out the exact location in a program from where the exception was raised.
Exceptions are Ruby's way of dealing with unexpected events. If you've ever made a typo in your code, causing your program to crash with a message like SyntaxError or NoMethodError , then you've seen exceptions in action. When you raise an exception in Ruby, the world stops and your program starts to shut down.
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With