This document discusses error handling in Ruby and Rails. It defines what an error is, how to report errors using exceptions or return values, and how to rescue from errors using begin/rescue/ensure blocks. It also covers topics like raising exceptions, the global error object $!, re-raising exceptions, and ensuring code is always run using ensure.
Code Fast, die() Early, Throw Structured ExceptionsJohn Anderson
Slides from a short talk given at January 2012 DC.pm. Covers "classic" exceptions in Perl as well as some libraries to make working with exceptions easier.
It contains different concepts of Object Oriented PHP like cloning of object, Inheritance, function overriding, Final function, Error Handling, Exception Handling, Custom error handling class, Uploading a file to the server with different criteria like file size, file type, file extension etc. are discussed in this presentation.
Kindly look at it and give comments to improve it as good as possible ways.
We <3 .rb
but - still .rb < perfect
This presentation shows some of the ways that this language, engineered for maximum programmer happiness and least surprise, can still have some nasty gotchas.
We <3> true
But - still .rb < perfect # => true
Though Ruby was allegedly "engineered to maximize programmer happiness", in part by adhering to the "principle of least surprise", Ruby still has some surprising and annoying gotchas. This presention contains an Array, er, a bunch of them, from programming-newbie gotchas to ones that still "get" grizzled veteran Rubyists. The talk these are from, approximately 45 minutes, may save you many hours of frustrated head-scratching (and bashing against the desk) later!
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Code Fast, die() Early, Throw Structured ExceptionsJohn Anderson
Slides from a short talk given at January 2012 DC.pm. Covers "classic" exceptions in Perl as well as some libraries to make working with exceptions easier.
It contains different concepts of Object Oriented PHP like cloning of object, Inheritance, function overriding, Final function, Error Handling, Exception Handling, Custom error handling class, Uploading a file to the server with different criteria like file size, file type, file extension etc. are discussed in this presentation.
Kindly look at it and give comments to improve it as good as possible ways.
We <3 .rb
but - still .rb < perfect
This presentation shows some of the ways that this language, engineered for maximum programmer happiness and least surprise, can still have some nasty gotchas.
We <3> true
But - still .rb < perfect # => true
Though Ruby was allegedly "engineered to maximize programmer happiness", in part by adhering to the "principle of least surprise", Ruby still has some surprising and annoying gotchas. This presention contains an Array, er, a bunch of them, from programming-newbie gotchas to ones that still "get" grizzled veteran Rubyists. The talk these are from, approximately 45 minutes, may save you many hours of frustrated head-scratching (and bashing against the desk) later!
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Welcome to the first live UiPath Community Day Dubai! Join us for this unique occasion to meet our local and global UiPath Community and leaders. You will get a full view of the MEA region's automation landscape and the AI Powered automation technology capabilities of UiPath. Also, hosted by our local partners Marc Ellis, you will enjoy a half-day packed with industry insights and automation peers networking.
📕 Curious on our agenda? Wait no more!
10:00 Welcome note - UiPath Community in Dubai
Lovely Sinha, UiPath Community Chapter Leader, UiPath MVPx3, Hyper-automation Consultant, First Abu Dhabi Bank
10:20 A UiPath cross-region MEA overview
Ashraf El Zarka, VP and Managing Director MEA, UiPath
10:35: Customer Success Journey
Deepthi Deepak, Head of Intelligent Automation CoE, First Abu Dhabi Bank
11:15 The UiPath approach to GenAI with our three principles: improve accuracy, supercharge productivity, and automate more
Boris Krumrey, Global VP, Automation Innovation, UiPath
12:15 To discover how Marc Ellis leverages tech-driven solutions in recruitment and managed services.
Brendan Lingam, Director of Sales and Business Development, Marc Ellis
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
The Metaverse and AI: how can decision-makers harness the Metaverse for their...Jen Stirrup
The Metaverse is popularized in science fiction, and now it is becoming closer to being a part of our daily lives through the use of social media and shopping companies. How can businesses survive in a world where Artificial Intelligence is becoming the present as well as the future of technology, and how does the Metaverse fit into business strategy when futurist ideas are developing into reality at accelerated rates? How do we do this when our data isn't up to scratch? How can we move towards success with our data so we are set up for the Metaverse when it arrives?
How can you help your company evolve, adapt, and succeed using Artificial Intelligence and the Metaverse to stay ahead of the competition? What are the potential issues, complications, and benefits that these technologies could bring to us and our organizations? In this session, Jen Stirrup will explain how to start thinking about these technologies as an organisation.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
Ruby & Rails Error Handling
1. Error Handling in Ruby & Rails
Simon Maynard - Bugsnag CTO
@snmaynard
2. What is Bugsnag?
• We help developers log and track their errors
• Ruby was the first language we supported
• Now support Python, PHP, Javascript, Node.js, iOS, Android & more!
• Processing millions of errors every day
3. What is AN ERROR?
An error occurs when code is unable to complete the task asked of it.
• Asked to do the impossible
Account.find(nil)
• A mistake in the code
account = Account.new
acccount.name #!?
4. What is AN ERROR?
• An unexpected case
case account.type
when "free" then #
when "paid" then #
else
# Unexpected!
end
• Failure of an external element
# Database down!
account.save
5. How to report an error?
• Raise an exception
• Only when the error is truly exceptional
• If the error is unexpected, or a sign of bad code
• Raising should be unexpected, it’s slow
6. How to report an error?
• Return an error value
• If its to be expected or part of "normal" operation
def find(id)
raise InvalidIdError, "#{id} id an invalid id" unless validate_id(id)
return data[id]
end
7. Raise Or Fail
• You can use raise to raise an exception.
• You can also use fail to raise an exception.
def func
fail "Not implemented"
rescue => e
raise unless e.message == "Not implemented"
end
8. Raise Syntax
raise MyError.new("Something Broke")
is the same as
raise MyError, "Something Broke"
9. Raise Syntax
raise "Something Broke"
is the same as
raise RuntimeError, "Something Broke"
11. Raise Syntax
You can also pass a backtrace when raising an exception
def assert(value)
raise(RuntimeError, "Something broke", caller) unless value
end
12. What does raise actually do?
• Raise does four things,
• Builds an exception object
• Sets the backtrace
• Sets the global error object ($!)
• Starts unwinding the stack
13. How does raise build the exception?
You might think that raise does this
def raise(klass, msg, trace)
exception = klass.new(message)
# ...
end
But actually it does this...
def raise(klass, msg, trace)
exception = klass.exception(message)
# ...
end
14. How does raise build the exception?
• Exception.exception
• The same as Exception.new()
• Exception#exception
• With no arguments, it returns self
• With a message, it returns a new exception with the message set
15. How does raise build the exception?
This means we can implement our own exception methods
class Account
def exception(message="Bad Account!")
ValidationError.new("#{message}: #{self.errors.inspect}")
end
end
then we can throw an instance of own object
raise account unless account.save
16. Global Error Object
$! contains a reference to the exception currently being raised
begin
raise
rescue
puts $!.inspect
end
You can also require “english” to use the slightly more readable
$ERROR_INFO
require "english"
begin
raise
rescue
puts $ERROR_INFO.inspect
end
17. rescue Syntax
begin
rescue MyError => error
end
will rescue all MyError exceptions
18. rescue Syntax
begin
rescue => error
end
is the same as
begin
rescue StandardError => error
end
19. Rescue Syntax
begin
rescue
end
is the same as
begin
rescue StandardError
end
20. Rescue Syntax
You can also supply a list of classes to rescue
begin
rescue MyError, IOError => error
end
21. One Line Rescue Syntax
value = raise rescue "fallback_value"
is the same as
value = begin
raise
rescue
"fallback_value"
end
22. Dynamic rescues
def match_message(regex)
mod = Module.new
(class << mod; self; end).instance_eval do
define_method(:===) do |e|
regex === e.message
end
end
mod
end
begin
raise "sample message"
rescue match_message(/sample/)
# Ignore
end
24. Raising in rescue
You can also change the exception message before re-raising
begin
raise
rescue => err
# Re raise with different message
raise err, “Different message”
end
25. Raising in rescue
You can raise in a rescue
def func
raise
rescue
raise "totally new exception"
end
You lose the context of the real error!
Don’t do this!
26. Raising in rescue
Instead you can keep a reference to the original exception
class MyError < StandardError
attr_accessor :original_exception
def initialize(msg, original_exception=$!)
super(msg)
self.original_exception = original_exception
end
end
def func
raise
rescue
raise MyError.new("Something broke")
end
27. Ensure Syntax
Ensure allows you to ensure that code is run, regardless of whether an exception
is raised or not.
begin
raise unless rand < 0.5
ensure
# Always run
end
28. ALTERNATIVE Syntax
You can also use these commands without a begin section
def func(arg)
raise
rescue
# Deal with exception
ensure
# Always run
end
29. Ensure Syntax
Be careful with return inside an ensure!
def func(arg)
raise
ensure
# This return swallows the exception
return 5
end
30. RETRY
You can also easily retry using the retry keyword
def func(arg)
attempts = 0
begin
attempts += 1
raise
rescue
retry if attempts < 3
end
end
32. Exception hierarchy
For example,
while true do
begin
line = STDIN.gets
# heavy processing
rescue Exception => e
puts "caught exception #{e}! ohnoes!"
end
end
This program is almost unkillable! Don’t catch Exception!
33. Exception Hierarchy
You can even prevent an exit call,
begin
exit(1) # Or abort()
rescue Exception
puts "Guess again!"
end
# Continue...
You can’t catch an exit!(1) however...
34. Raise is a method
• Raise is just a method on Kernel
• So we can override it!
35. Raise is a method
We can add debugging information to each raise
module RaiseDebug
def raise(*args)
super *args
rescue Exception
puts "Raising exception: #{$!.inspect}"
super *args
end
end
class Object
include RaiseDebug
end
36. Uncaught Errors
We can use a combination of $! and the ruby exit handler to log uncaught errors
at_exit do
if $!
open('error.log', 'a') do |log_file|
error = {
timestamp: Time.now.utc,
message: $!.message,
trace: $!.backtrace,
}
log_file.write(error.to_json)
end
end
end
37. Throw/Catch
Ruby can also throw, but its not for errors.
Use throw to unwrap the stack in a non-exceptional case, saves you from using
multiple break commands
INFINITY = 1.0 / 0.0
catch (:done) do
1.upto(INFINITY) do |i|
1.upto(INFINITY) do |j|
if some_condition
throw :done
end
end
end
end
38. How does rails deal with exceptions?
When there is an error in your rails app, ideally we want these things to happen
• 500 page rendered to show the user something went wrong
• Error logged with enough information so we can fix it
• Rails to continue serving requests
39. How does rails deal with exceptions?
• Rails uses a Rack app to process every request.
• Rack apps have a middleware stack
• You can easily add your own middleware so you can execute code on every
request
config.middleware.use(new_middleware, args)
config.middleware.insert_before(existing_middleware, new_middleware, args)
config.middleware.insert_after(existing_middleware, new_middleware, args)
config.middleware.delete(middleware)
41. Example RACK Middleware
Here is an example of a no-op middleware
module OurMiddleware
class Rack
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
end
end
end
42. Example RACK Middleware
• Initialize called when rails app starts
• Takes a single parameter, which is the next middleware in the stack
• Perform any other initialization for your middleware
def initialize(app)
@app = app
end
43. Example RACK Middleware
• Call is called for every request
• @app.call calls the next middleware in the stack (or your app itself)
def call(env)
response = @app.call(env)
end
44. Rendering a 500 page
• Rails uses this to handle errors, for example in ShowExceptions middleware
def call(env)
@app.call(env)
rescue Exception => exception
raise exception if env['action_dispatch.show_exceptions'] == false
render_exception(env, exception)
end
• Rails rescues the exception here, and renders a nice 500 error page
45. Bugsnag Logging middleware
• Here is a simplified version of the Bugsnag error logging middleware
def call(env)
@app.call(env)
rescue Exception => exception
Bugsnag.notify(exception)
raise
end
• But you need to make sure this goes in you middleware stack JUST before you
render the 500 page!
46. SHOW The middleware stack
• Rails has given you an awesome tool to show your middleware stack
$ rake middleware
...
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use Bugsnag::Rack
...
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
...
run YourApp::Application.routes
47. Better Errors
• https://github.com/charliesome/better_errors
• Better version of DebugExceptions, used in development on Rails
• Allows you to debug crashes when they happen
48. Hammertime
• https://github.com/avdi/hammertime
• Allows you to debug exception raises in real time in Ruby apps
49. PRY RESCUE
• https://github.com/ConradIrwin/pry-rescue
• Allows you to debug uncaught exceptions in real time in Ruby apps
50. Bugsnag
• http://bugsnag.com
• Tracks and groups your errors from development and production
• Get notified when someone on production sees a crash!
51. Find out more
• Avdi Grimm has a great book on Ruby failure handling - I highly recommend it
(http://exceptionalruby.com/)
• When looking into rails error handling, delving into Rails source is recommended.
Return an error value if its common or people will use to test Validation function shouldnt raise if invalid e.g mongoid find raising by default, at least you can change if you want
raise = fail raise common some use fail to be when failing for first time, raise in rescue blocks
exception is like to_s, but for exceptions
Can attach exception methods to objects easily, so they can be raised
These are just examples, empty rescue blocks are a code smell, at least have a log in there!
Bad as it catches all StandardErrors, you should catch explicit exception types, more on that later
Rescue calls === on the error and the object passed to rescue, so we can override
This is a common pattern in ruby, getting more popular - rails does it when you have an error in your view for example converts to template error
Exception hierarchy shows why you should never catch exception
Be specific when you catch something
Note here I rescue exception, but I always re-raise :-)
Sinatra uses this when using etags i believe, to prevent recalculating a still valid response
Middleware performance is important Crashes in middleware are very bad