Slide 1

Slide 1 text

How to get to zero unhandled exceptions in production Radoslav Stankov 26/05/2018

Slide 2

Slide 2 text

Radoslav Stankov @rstankov blog.rstankov.com github.com/rstankov
 twitter.com/rstankov

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

Happy Friday ! " Fix bugs # Goodies features $ Pay technical dept % Catchup on projects & Fix exceptions

Slide 14

Slide 14 text

Happy Friday ! " Fix bugs # Goodies features $ Pay technical dept % Catchup on projects & Fix exceptions

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Back to basics

Slide 17

Slide 17 text


 http://exceptionalruby.com/


Slide 18

Slide 18 text

def perform do_something rescue end

Slide 19

Slide 19 text

def perform do_something rescue end

Slide 20

Slide 20 text

def perform do_something rescue end

Slide 21

Slide 21 text

def perform do_something rescue SpecificError end

Slide 22

Slide 22 text

def perform do_something rescue SpecificError # NOTE(rstankov): Reason to return nil nil end

Slide 23

Slide 23 text

def perform do_something rescue SpecificError # NOTE(rstankov): Reason to return nil nil end Your name, not mine '

Slide 24

Slide 24 text

def perform do_something rescue SpecificError # NOTE(rstankov): Reason to return nil nil end

Slide 25

Slide 25 text

def perform do_something rescue NetworkErrors # NOTE(rstankov): WiFi Sucks nil end

Slide 26

Slide 26 text

module NetworkErrors extend self ERRORS = [ EOFError, Errno::ECONNRESET, Errno::EINVAL, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Timeout::Error, # ... ] def ===(error) ERRORS.any? { |error_class| error_class === error } end end

Slide 27

Slide 27 text

– saw it in a tweet once “A mature Rails project is one, that uses every popular (or not so popular) Ruby networking gem.” (

Slide 28

Slide 28 text

– saw it in a tweet once “A mature Rails project is one, that uses every popular (or not so popular) Ruby networking gem.” (

Slide 29

Slide 29 text

module NetworkErrors extend self ERRORS = [ # ... Faraday::ConnectionFailed, Faraday::TimeoutError, RestClient::BadGateway, RestClient::BadRequest, # ... ] def ===(error) ERRORS.any? { |error_class| error_class === error } end end

Slide 30

Slide 30 text

if user.ship_subscription.blank? Raven.capture_message "Missing ship subscription", extra: { user_id: user.id } return :no_subscription end

Slide 31

Slide 31 text

Monitoring

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

Raven.configure do |config| # Note(rstankov): Exclude un actionable errors config.excluded_exceptions = [ 'Rack::Timeout::RequestExpiryError', 'Rack::Timeout::RequestTimeoutException', 'ActionController::RoutingError', 'ActionController::InvalidAuthenticityToken', 'ActionDispatch::ParamsParser::ParseError', 'Sidekiq::Shutdown', ] end

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

account.subscription.status

Slide 42

Slide 42 text

account.subscription&.status

Slide 43

Slide 43 text

account.subscription&.status

Slide 44

Slide 44 text

Steps to fix )

Slide 45

Slide 45 text

0. Check for other accounts without subscription Steps to fix )

Slide 46

Slide 46 text

0. Check for other accounts without subscription 1. Find out why account doesn't have a subscription Steps to fix )

Slide 47

Slide 47 text

0. Check for other accounts without subscription 1. Find out why account doesn't have a subscription 2. Fix the problem Steps to fix )

Slide 48

Slide 48 text

0. Check for other accounts without subscription 1. Find out why account doesn't have a subscription 2. Fix the problem 3. Add missing subscriptions to this accounts Steps to fix )

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

– Brian Kernighan and Rob Pike, The Practice of Programming “Exceptions shouldn't be expected” Use exceptions only for exceptional situations. […] Exceptions are often overused. Because they distort the flow of control, they can lead to convoluted constructions that are prone to bugs. It is hardly exceptional to fail to open a file; generating an exception in this case strikes us as over-engineering.

Slide 52

Slide 52 text

ArgumentError: invalid byte sequence in UTF-8

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

# NOTE(rstankov): Fix invalid byte sequence in UTF-8. More info: # - https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences module Utf8Sanitize extend self def call(string) return if string.nil? string.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '' ) end end

Slide 55

Slide 55 text


 https://graphql.org/


Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

Which query causes this issue? *

Slide 59

Slide 59 text

class Frontend::GraphqlController < Frontend::BaseController before_action :ensure_query def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private # ... def handle_error(e) if Rails.env.development? logger.error e.message logger.error e.backtrace.join("\n") render json: { message: e.message, backtrace: e.backtrace }, status: 500 elsif Rails.env.test? p e.message # rubocop:disable Rails/Output p e.backtrace # rubocop:disable Rails/Output else Raven.capture_exception(e, extra: { query: query }) end end end

Slide 60

Slide 60 text

class Frontend::GraphqlController < Frontend::BaseController before_action :ensure_query def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private # ... def handle_error(e) if Rails.env.development? logger.error e.message logger.error e.backtrace.join("\n") render json: { message: e.message, backtrace: e.backtrace }, status: 500 elsif Rails.env.test? p e.message # rubocop:disable Rails/Output p e.backtrace # rubocop:disable Rails/Output else Raven.capture_exception(e, extra: { query: query }) end end end

Slide 61

Slide 61 text

class Frontend::GraphqlController < Frontend::BaseController before_action :ensure_query def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private # ... def handle_error(e) if Rails.env.development? logger.error e.message logger.error e.backtrace.join("\n") render json: { message: e.message, backtrace: e.backtrace }, status: 500 elsif Rails.env.test? p e.message # rubocop:disable Rails/Output p e.backtrace # rubocop:disable Rails/Output else Raven.capture_exception(e, extra: { query: query }) end end end

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

Graph::Query = GraphQL::ObjectType.define do name 'Query' field :post do type !Graph::Types::PostType argument :id, !types.ID resolve ->(_obj, inputs, _ctx) { Post.find(inputs[:id]) } end end

Slide 65

Slide 65 text

Graph::Query = GraphQL::ObjectType.define do name 'Query' field :post do type Graph::Types::PostType argument :id, !types.ID resolve ->(_obj, inputs, _ctx) { Post.find_by(id: inputs[:id]) } end end

Slide 66

Slide 66 text

class Graph::Mutations::CollectionAddPost < Graph::Resolvers::Mutation node :collection, type: Collection input :post_id, !types.ID authorize: Authorization::MANAGE returns Graph::Types::PostType def perform post = Post.find inputs[:post_id] Collections.add_post collection, post post end end

Slide 67

Slide 67 text

class Graph::Resolvers::Mutation # ... def call pre_proccess handle_result perform rescue ActiveRecord::RecordInvalid, MiniForm::InvalidForm => e errors_from_record(e.record) rescue ActiveRecord::RecordNotFound error :base, :record_not_found rescue CanCan::AccessDenied error_access_denied end # ... end

Slide 68

Slide 68 text


 https://sidekiq.org/


Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

class Achievements::Worker < ApplicationJob def perform(achievement, user)
 HandleRaceCondition.call do Achievements::Create.call achievement, user end end end

Slide 71

Slide 71 text

module HandleRaceCondition extend self UNIQUE_ACTIVE_RECORD_ERROR = 'has already been taken'.freeze def call retries ||= 2 yield rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation retries -= 1 raise unless retries.nonzero? retry rescue ActiveRecord::RecordInvalid => e raise unless e.message.include? UNIQUE_ACTIVE_RECORD_ERROR retries -= 1 raise unless retries.nonzero? retry end end

Slide 72

Slide 72 text

Notifications::FanOutWorker Notifications::ScheduleWorker Notifications::DeliveryWorker Notifications.notify_about :kind, object

Slide 73

Slide 73 text

Notifications::FanOutWorker Notifications::ScheduleWorker Notifications::DeliveryWorker Notifications.notify_about :kind, object kind, object

Slide 74

Slide 74 text

Notifications::FanOutWorker Notifications::ScheduleWorker Notifications::DeliveryWorker Notifications.notify_about :kind, object kind, object kind, object, subscriber

Slide 75

Slide 75 text

Notifications::FanOutWorker Notifications::ScheduleWorker Notifications::DeliveryWorker Notifications.notify_about :kind, object kind, object kind, object, subscriber kind, object, subscriber, channel

Slide 76

Slide 76 text

class Notifications::ScheduleWorker < ApplicationJob include ActiveJobHandleDeserializationError queue_as :notifications def perform(kind:, object:, subscriber_id:) Notifications::Schedule.call( kind: kind, object: object, subscriber_id: subscriber_id, ) end end

Slide 77

Slide 77 text

module ActiveJobHandleDeserializationError include ActiveJobRetriesCount extend ActiveSupport::Concern included do rescue_from ActiveJob::DeserializationError do retry_job wait: 5.minutes if retries_count.zero? end end end

Slide 78

Slide 78 text

module ActiveJobHandleDeserializationError include ActiveJobRetriesCount extend ActiveSupport::Concern included do rescue_from ActiveJob::DeserializationError do retry_job wait: 5.minutes if retries_count.zero? end end end

Slide 79

Slide 79 text

module ActiveJobRetriesCount extend ActiveSupport::Concern included do attr_accessor :retries_count end def initialize(*arguments) super @retries_count ||= 0 end def deserialize(job_data) super @retries_count = job_data['retries_count'] || 0 end def serialize hash = super.merge('retries_count' => retries_count || 0) # NOTE(rstankov): Workaround for Rails bug # When arguments raise `ActiveJob::DeserializationError` arguments are blank hash['arguments'] ||= @serialized_arguments if @serialized_arguments hash end def retry_job(options) @retries_count = (retries_count || 0) + 1 super(options) end end

Slide 80

Slide 80 text

class Notifications::Deliver::Worker < ApplicationJob include ActiveJobHandleNetworkErrors queue_as :notifications def perform(event) Notifications::Deliver.call(event) end end

Slide 81

Slide 81 text

module ActiveJobHandleNetworkErrors include ActiveJobRetriesCount extend ActiveSupport::Concern included do rescue_from(NetworkErrors) do if retries_count <= 10 retry_job wait: 5.minutes else
 raise e end end end end

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

Thanks +