Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually create exception with message and backtrace

Tags:

exception

ruby

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?

like image 887
Juanito Fatas Avatar asked May 10 '16 09:05

Juanito Fatas


People also ask

How to throw exception with custom message in Java?

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.

What is Backtrace in Ruby?

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.

What are Ruby exceptions?

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.


3 Answers

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)
like image 153
sawa Avatar answered Sep 29 '22 20:09

sawa


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.

like image 32
Juanito Fatas Avatar answered Sep 29 '22 19:09

Juanito Fatas


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.

like image 37
XavM Avatar answered Sep 29 '22 19:09

XavM