Slide 1

Slide 1 text

Living without Exceptions Radoslav Stankov 07/09/2019

Slide 2

Slide 2 text

!

Slide 3

Slide 3 text

Radoslav Stankov @rstankov rstankov.com

Slide 4

Slide 4 text

https://tips.rstankov.com

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

No content

Slide 14

Slide 14 text

" Happy Friday # Bug Duty ⚔ Strike Team 4 8 20 developers count

Slide 15

Slide 15 text

1 developers count " Happy Friday

Slide 16

Slide 16 text

% Fix bugs & Fix exceptions ' Bump dependancies ( Pay technical dept ) Catchup on projects " Happy Friday

Slide 17

Slide 17 text

% Fix bugs & Fix exceptions ' Bump dependancies ( Pay technical dept ) Catchup on projects " Happy Friday

Slide 18

Slide 18 text

% Fix bugs & Fix exceptions ' Bump dependancies ( Pay technical dept ) Catchup on projects " Happy Friday

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

“Have process around exceptions.” * Rado's tip

Slide 21

Slide 21 text

Back to basics

Slide 22

Slide 22 text

http://exceptionalruby.com/

Slide 23

Slide 23 text

def perform do_something rescue end

Slide 24

Slide 24 text

def perform do_something rescue end

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

def perform do_something rescue SpecificError end

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

“Be explicit around the exceptions. Handle specific errors and have explanations of why they happen.” * Rado's tip

Slide 32

Slide 32 text

Monitoring

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

No content

Slide 37

Slide 37 text

“Split web and background processes errors into separate projects” * Rado's tip

Slide 38

Slide 38 text

#engineering-exceptions

Slide 39

Slide 39 text

“Have a Slack channel where every new exception is being logged. Log deployments in this channel as well, so you can correlate.” * Rado's tip

Slide 40

Slide 40 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 41

Slide 41 text

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

Slide 42

Slide 42 text

“Reduce noise. See only exceptional errors in your tracker.” * Rado's tip

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

ArgumentError: invalid byte sequence in UTF-8 &

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

“I put most of the code related to exceptions in a single module named Handle” * Rado's tip

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

account.subscription.status

Slide 54

Slide 54 text

account.subscription&.status

Slide 55

Slide 55 text

account.subscription&.status

Slide 56

Slide 56 text

, Steps to fix -

Slide 57

Slide 57 text

✅ Check for other accounts without a subscription , Steps to fix -

Slide 58

Slide 58 text

✅ Check for other accounts without a subscription , Steps to fix -

Slide 59

Slide 59 text

✅ Check for other accounts without a subscription ✅ Find out why those accounts don't have a subscription , Steps to fix -

Slide 60

Slide 60 text

✅ Check for other accounts without a subscription ✅ Find out why those accounts don't have a subscription , Steps to fix -

Slide 61

Slide 61 text

✅ Check for other accounts without a subscription ✅ Find out why those accounts don't have a subscription ✅ Fix this / , Steps to fix -

Slide 62

Slide 62 text

✅ Check for other accounts without a subscription ✅ Find out why those accounts don't have a subscription ✅ Fix this / , Steps to fix -

Slide 63

Slide 63 text

✅ Check for other accounts without a subscription ✅ Find out why those accounts don't have a subscription ✅ Fix this / ✅ Add missing subscriptions to accounts , Steps to fix -

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

“Don't hide exceptions. Fix root causes.” * Rado's tip

Slide 67

Slide 67 text

if account.ship_subscription.blank? ErrorReporting.capture "Missing ship subscription", account_id: account.id return :no_subscription end

Slide 68

Slide 68 text

“I have a module named ErrorReporting, which helps me capture errors that won't get to the user and provides a centralized place for error tracking.” * Rado's tip

Slide 69

Slide 69 text

https://graphql.org/

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

Which query causes this issue? 0

Slide 74

Slide 74 text

class Frontend::GraphqlController < Frontend::BaseController before_action :authenticate def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private def authenticate # ... 
 ErrorReporting.assign_user(@user) end
 def handle_error(error) if Rails.env.development? logger.error error.message logger.error error.backtrace.join("\n") render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 elsif Rails.env.test? p error.message p error.backtrace render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 else ErrorReporting.capture(e, query: query) render json: { error: { message: 'SERVER_ERROR' }, data: {} }, status: 500 end end end

Slide 75

Slide 75 text

class Frontend::GraphqlController < Frontend::BaseController before_action :authenticate def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private def authenticate # ... 
 ErrorReporting.assign_user(@user) end
 def handle_error(error) if Rails.env.development? logger.error error.message logger.error error.backtrace.join("\n") render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 elsif Rails.env.test? p error.message p error.backtrace render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 else ErrorReporting.capture(e, query: query) render json: { error: { message: 'SERVER_ERROR' }, data: {} }, status: 500 end end end

Slide 76

Slide 76 text

class Frontend::GraphqlController < Frontend::BaseController before_action :authenticate def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private def authenticate # ... 
 ErrorReporting.assign_user(@user) end
 def handle_error(error) if Rails.env.development? logger.error error.message logger.error error.backtrace.join("\n") render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 elsif Rails.env.test? p error.message p error.backtrace render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 else ErrorReporting.capture(e, query: query) render json: { error: { message: 'SERVER_ERROR' }, data: {} }, status: 500 end end end

Slide 77

Slide 77 text

class Frontend::GraphqlController < Frontend::BaseController before_action :authenticate def index render json: Graph::Schema.execute(query, variables: variables, context: context) rescue => e handle_error e end private def authenticate # ... 
 ErrorReporting.assign_user(@user) end
 def handle_error(error) if Rails.env.development? logger.error error.message logger.error error.backtrace.join("\n") render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 elsif Rails.env.test? p error.message p error.backtrace render json: { error: { message: error.message, backtrace: error.backtrace } }, status: 500 else ErrorReporting.capture(e, query: query) render json: { error: { message: 'SERVER_ERROR' }, data: {} }, status: 500 end end end

Slide 78

Slide 78 text

“Invest in your monitoring and exception traceability. When you have a hard time racing an exception. Ask yourself - what more information I need? 0 Then add it.” * Tip

Slide 79

Slide 79 text

https://sidekiq.org/

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

Use action

Slide 82

Slide 82 text

Use action Achievements::Job

Slide 83

Slide 83 text

Use action Achievements::Job Achievement
 (unique)

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

Use action Achievements::Job Achievement
 (unique) Use action Achievements::Job Achievement
 (unique)

Slide 86

Slide 86 text

Use action Achievements::Job Achievement
 (unique) Use action Achievements::Job Achievement
 (unique) &

Slide 87

Slide 87 text

Use action Achievements::Job Achievement
 (unique) Use action Achievements::Job PG::UniqueViolation &

Slide 88

Slide 88 text

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

Slide 89

Slide 89 text

class Achievements::Job < ApplicationJob def perform(achievement, user) Handle::RaceCondition.call do Achievements::Create.call achievement, user end end end

Slide 90

Slide 90 text

module Handle::RaceCondition 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 91

Slide 91 text

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

Slide 92

Slide 92 text

Errno::ECONNRESET &

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

class Notifications::DeliverJob < ApplicationJob queue_as :notifications def perform(event) Notifications::Deliver.call(event)
 rescue Errno::ECONNRESET
 retry_job end end

Slide 96

Slide 96 text

Errno:: EOFError &

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

class Notifications::DeliverJob < ApplicationJob queue_as :notifications def perform(event) Notifications::Deliver.call(event)
 rescue Errno::ECONNRESET, EOFError
 retry_job end end

Slide 99

Slide 99 text

class Notifications::DeliverJob < ApplicationJob queue_as :notifications def perform(event) Notifications::Deliver.call(event)
 rescue Errno::ECONNRESET, EOFError, Timeout::Error
 retry_job end end

Slide 100

Slide 100 text

class Notifications::DeliverJob < ApplicationJob queue_as :notifications def perform(event) Notifications::Deliver.call(event)
 rescue Errno::ECONNRESET, EOFError, Timeout::Error, ... 1
 retry_job end end

Slide 101

Slide 101 text

module Handle::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 102

Slide 102 text

class Notifications::Deliver < ApplicationJob queue_as :notifications def perform(event) Notifications::Deliver.call(event)
 rescue Handle::NetworkErrors retry_job end end

Slide 103

Slide 103 text

class Notifications::Deliver::Job < ApplicationJob retry_on(*::Handle::NetworkErrors::ERRORS, wait: 2.minutes, attempts: 5) queue_as :notifications def perform(event) Notifications::Deliver.call(event) end end

Slide 104

Slide 104 text

class Notifications::Deliver::Job < ApplicationJob include Handle::Job::NetworkErrors queue_as :notifications def perform(event) Notifications::Deliver.call(event) end end

Slide 105

Slide 105 text

module Handle::Job::NetworkErrors def self.included(job) job.retry_on( *::Handle::NetworkErrors::ERRORS, wait: 2.minutes, attempts: 50 ) do |job, exception| ErrorReporting.job_discarded(job, exception) end end end

Slide 106

Slide 106 text

module Handle::Job::NetworkErrors def self.included(job) job.retry_on( *::Handle::NetworkErrors::ERRORS, wait: 2.minutes, attempts: 50 ) do |job, exception| ErrorReporting.job_discarded(job, exception) end end end

Slide 107

Slide 107 text

No content

Slide 108

Slide 108 text

2

Slide 109

Slide 109 text

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

Slide 110

Slide 110 text

ActiveJob::DeserializationError &

Slide 111

Slide 111 text

No content

Slide 112

Slide 112 text

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

Slide 113

Slide 113 text

class Notifications::ScheduleJob < ApplicationJob include Handle::Job::DeserializationError queue_as :notifications def perform(kind:, object:, subscriber_id:) Notifications::Schedule.call( kind: kind, object: object, subscriber_id: subscriber_id, ) end end

Slide 114

Slide 114 text

“Have tooling around handling common exceptions. Make it a no-brainer to process everyday errors.” * Rado's tip

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

Recap

Slide 118

Slide 118 text

* Be explicit around the exceptions * Reduce noise * Don't hide exceptions * Invest in your monitoring * Have tooling around handling exceptions 3 Recap

Slide 119

Slide 119 text

https://tips.rstankov.com/p/tips-exceptions

Slide 120

Slide 120 text

No content