Skip to content

Commit

Permalink
Improve DeliveryException
Browse files Browse the repository at this point in the history
Improve DeliveryException

The sparkpost api returns errors in the following format:
```
{
  "errors": [
    {
      "message": "Message generation rejected",
      "description": "recipient address suppressed due to customer
policy",
      "code": "1902"
    }
  ]
...
}

```

`message`, `description`, and `code` are now available on the
DeliveryException instance as: `service_message`,
`service_description`, `service_code`

The original message is preserved so it will not break any legacy
parsing written by users.
  • Loading branch information
ksykulev committed May 8, 2016
1 parent e321420 commit 5a41f89
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/sparkpost_rails/exceptions.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
module SparkPostRails
class DeliveryException < StandardError
attr_reader :service_message, :service_description, :service_code

def initialize(message)
errors = [*message].first

if errors.is_a?(Hash)
@service_message = errors['message']
@service_description = errors['description']
@service_code = errors['code']
end

super(message)
end
end
end
65 changes: 65 additions & 0 deletions spec/exceptions_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
require 'spec_helper'

describe SparkPostRails::DeliveryException do
subject { SparkPostRails::DeliveryException.new(error) }

describe 'string' do
let(:error) { 'Some delivery error' }

it 'preserves original message' do
begin
raise subject
rescue SparkPostRails::DeliveryException => err
expect(error).to eq(err.message)
end
end
end

describe 'array with error details' do
let(:error) { [{ 'message' => 'Message generation rejected', 'description' => 'recipient address suppressed due to customer policy', 'code' => '1902' }] }

it 'assigns message' do
expect(subject.service_message).to eq('Message generation rejected')
end

it 'assigns description' do
expect(subject.service_description).to eq('recipient address suppressed due to customer policy')
end

it 'assigns code' do
expect(subject.service_code).to eq('1902')
end

it 'preserves original message' do
begin
raise subject
rescue SparkPostRails::DeliveryException => err
expect(error.to_s).to eq(err.message)
end
end
end

describe 'array with partial details' do
let(:error) { [{ 'message' => 'end of world' }] }

it 'assigns message' do
expect(subject.service_message).to eq('end of world')
end

it 'assigns description' do
expect(subject.service_description).to be nil
end

it 'assigns code' do
expect(subject.service_code).to be nil
end

it 'preserves original message' do
begin
raise subject
rescue SparkPostRails::DeliveryException => err
expect(error.to_s).to eq(err.message)
end
end
end
end

0 comments on commit 5a41f89

Please sign in to comment.