diff --git a/README.md b/README.md index a306081..13104a0 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,19 @@ client.create_private_message( #=> Creates a private messages b ``` +You can handle some basic errors by rescuing from certain error classes and inspecting the response object passed to those errors: + +```ruby +begin + client.create_group({ name: 'NO' }) +rescue DiscourseApi::UnprocessableEntity => error + # `body` is something like `{ errors: ["Name must be at least 3 characters"] }` + # This outputs "Name must be at least 3 characters" + puts error.response.body['errors'].first +end +``` + +Check out [lib/discourse_api/error.rb](lib/discourse_api/error.rb) and [lib/discourse_api/client.rb](lib/discourse_api/client.rb)'s `handle_error` method for the types of errors raised by the API. ## Contributing diff --git a/lib/discourse_api/client.rb b/lib/discourse_api/client.rb index 9070ed0..391070c 100644 --- a/lib/discourse_api/client.rb +++ b/lib/discourse_api/client.rb @@ -138,13 +138,13 @@ def request(method, path, params={}) def handle_error(response) case response.status when 403 - raise DiscourseApi::UnauthenticatedError.new(response.env[:body]) + raise DiscourseApi::UnauthenticatedError.new(response.env[:body], response.env) when 404, 410 - raise DiscourseApi::NotFoundError.new(response.env[:body]) + raise DiscourseApi::NotFoundError.new(response.env[:body], response.env) when 422 - raise DiscourseApi::UnprocessableEntity.new(response.env[:body]) + raise DiscourseApi::UnprocessableEntity.new(response.env[:body], response.env) when 429 - raise DiscourseApi::TooManyRequests.new(response.env[:body]) + raise DiscourseApi::TooManyRequests.new(response.env[:body], response.env) when 500...600 raise DiscourseApi::Error.new(response.env[:body]) end diff --git a/lib/discourse_api/error.rb b/lib/discourse_api/error.rb index 11a450a..9124aa0 100644 --- a/lib/discourse_api/error.rb +++ b/lib/discourse_api/error.rb @@ -1,5 +1,11 @@ module DiscourseApi class DiscourseError < StandardError + attr_reader :response + + def initialize(message, response = nil) + super(message) + @response = response + end end class Error < DiscourseError