<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sebastian Wilgosz on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Wilgosz on Medium]]></description>
        <link>https://medium.com/@swilgosz?source=rss-4aecfa61ff5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sebastian Wilgosz on Medium</title>
            <link>https://medium.com/@swilgosz?source=rss-4aecfa61ff5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:39:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swilgosz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handling exceptions in Rails API applications]]></title>
            <link>https://medium.com/@swilgosz/handling-exceptions-in-rails-api-applications-b276efa7e796?source=rss-4aecfa61ff5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b276efa7e796</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Sebastian Wilgosz]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 21:39:56 GMT</pubDate>
            <atom:updated>2020-06-17T21:44:42.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3b17allssowxOljXB6u0Q.jpeg" /></figure><p>Handling exceptions in your API applications is quite an important thing, and if you want to keep things DRY, you should think about how to do it in the proper way. In our <a href="https://www.udemy.com/ruby-on-rails-api-the-complete-guide/">Ruby on Rails API course</a>, I’ve shown how to implement the error handling using ErrorSerializer and FastJsonapi gem, and here I’m going to show you an even better approach to this topic when you can unify EVERY error across the whole API application.</p><h3>The final approach</h3><p>There is no point to cover the whole thought process of how I came with the final result, but if you’re interested in any particular part just say it in the comments. The basic assumptions were to keep things DRY and unified across the whole application.</p><p>So here is the code.</p><blockquote>Note: Check Out my <a href="https://driggl.com/blog/a/json-api-errors-handler">JsonApiErrorsHandler gem</a> when this concept is raised into the next level!</blockquote><h4>The standard error.</h4><pre># app/lib/errors/standard_error.rb</pre><pre>module Errors <br>  class StandardError &lt; ::StandardError <br>    def initialize(title: nil, detail: nil, status: nil, source: {})<br>      <a href="http://twitter.com/title">@title</a> = title || &quot;Something went wrong&quot; <br>      <a href="http://twitter.com/detail">@detail</a> = detail || &quot;We encountered unexpected error, but our developers had been already notified about it&quot; <br>      <a href="http://twitter.com/status">@status</a> = status || 500 <br>      <a href="http://twitter.com/source">@source</a> = source.deep_stringify_keys <br>    end <br>    <br>    def to_h <br>      { status: status, title: title, detail: detail, source: source } <br>    end <br>    def serializable_hash <br>      to_h <br>    end <br>    <br>    def to_s <br>      to_h.to_s <br>    end<br> <br>    attr_reader :title, :detail, :status, :source <br>  end <br>end</pre><p>First of all, we needed to have the Base error, which will be a fallback for any exception risen by our application. As we use <a href="https://jsonapi.org/">JSON API</a> in every server’s response, we wanted to always return an error in the format that JSON API describes.</p><p>We extracted all error-specific parts for every HTML status code we wanted to support, having a fallback to <em>500.</em></p><h3>More detailed errors</h3><p>As you can see this basic error was just a scaffold we could use to override particular attributes of the error object. Having that implemented, we were able to instantiate several case-specific errors to deliver more descriptive messages to our clients.</p><pre># app/lib/errors/unauthorized.rb </pre><pre>module Errors <br>  class Unauthorized &lt; Errors::StandardError <br>    def initialize <br>      super(<br>        title: &quot;Unauthorized&quot;, <br>        status: 401, <br>        detail: message || &quot;You need to login to authorize this request.&quot;, <br>        source: { pointer: &quot;/request/headers/authorization&quot; }<br>      ) <br>    end <br>  end <br>end</pre><pre># app/lib/errors/not_found.rb </pre><pre>module Errors <br>  class NotFound &lt; Errors::StandardError <br>    def initialize <br>      super(<br>        title: &quot;Record not Found&quot;, <br>        status: 404, <br>        detail: &quot;We could not find the object you were looking for.&quot;, <br>        source: { pointer: &quot;/request/url/:id&quot; }<br>      )<br>    end<br>  end<br>end</pre><p>All errors are very clean and small, without any unnecessary logic involved. That’s reasonable as we don’t want to give them an opportunity to fail in an unexpected way, right?</p><p>Anyway defining the error objects is only half of the job.</p><h3>Serializing the error in Ruby Application</h3><p>This approach above allowed us to use something like:</p><pre># app/controllers/articles_controller.rb<br>... </pre><pre>def show <br>  Article.find(params[:id]) <br>rescue ActiveRecord::RecordNotFound<br>  e = Errors::NotFound.new <br>  render json: ErrorSerializer.new(e), status: e.status <br>end </pre><pre>...</pre><p>To serialize the standard responses we use <a href="https://driggl.com/blog/a/from-activemodel-serializers-to-fast-jsonapi"><em>fast_jsonapi</em> gem from Netflix</a>. It’s quite nice for the usual approach, but for error handling not so much so we decided to write our own <em>ErrorSerializer</em>.</p><pre># app/serializers/error_serializer.rb </pre><pre>class ErrorSerializer <br>  def initialize(error) <br>    @error = error <br>  end </pre><pre>  def to_h <br>    serializable_hash <br>  end <br>  <br>  def to_json(payload) <br>    to_h.to_json <br>  end </pre><pre>  private </pre><pre>  def serializable_hash <br>    { errors: Array.wrap(error.serializable_hash).flatten } <br>  end <br>  <br>  attr_reader :error <br>end</pre><p>The logic is simple. It accepts an object with <em>status</em>, <em>title</em>, <em>detail</em> and <em>source</em> methods, and creates the serialized responses in the format of:</p><pre># json response </pre><pre>{ <br>  &quot;errors&quot;: [ <br>    { <br>      &quot;status&quot;: 401, <br>      &quot;title&quot;: &quot;Unauthorized&quot;, <br>      &quot;detail&quot;: &quot;You need to login to authorize this request.&quot;, <br>      &quot;source&quot;: { <br>        &quot;pointer&quot;: &quot;/request/headers/authorization&quot; <br>      } <br>    } <br>  ] <br>}</pre><p>The only problem here is that handling all of those errors in every action of the system will end up with a lot of code duplications which is not very DRY, is it? I could just raise proper errors in the services, but standard errors, like ActiveRecord::RecordNotFound would be tricky. This is then what we ended up within our API ApplicationController:</p><pre># app/controllers/application_controller.rb </pre><pre>class ApplicationController &lt; ActionController::API <br>  ... <br>  include Api::ErrorHandler <br>  ... <br>end</pre><p>We just included the <em>ErrorHandler</em> module, where we implemented all mappings and the logic responsible for all error handling.</p><pre>module Api::ErrorHandler <br>  extend ActiveSupport::Concern <br>  ERRORS = {<br>    &#39;ActiveRecord::RecordNotFound&#39; =&gt; &#39;Errors::NotFound&#39;, <br>    &#39;Driggl::Authenticator::AuthorizationError&#39; =&gt; &#39;Errors::Unauthorized&#39;, <br>    &#39;Pundit::NotAuthorizedError&#39; =&gt; &#39;Errors::Forbidden&#39;<br>  } </pre><pre>  included do <br>    rescue_from(StandardError, with: lambda { |e| handle_error(e) })<br>  end <br>  <br>  private <br>  <br>  def handle_error(e) <br>    mapped = map_error(e) # notify about unexpected_error <br>    unless mapped mapped ||= Errors::StandardError.new <br>    render_error(mapped) <br>  end <br> <br>  def map_error(e) <br>    error_klass = e.class.name <br>    return e if ERRORS.values.include?(error_klass) <br>    ERRORS[error_klass]&amp;.constantize&amp;.new <br>  end </pre><pre>  def render_error(error) <br>    render json: Api::V1::ErrorSerializer.new([error]), status: error.status <br>  end <br>end</pre><p>At the top, we added a nice mapper for all errors we expect to happen somewhere. Then we rescue from the <a href="https://blog.honeybadger.io/understanding-the-ruby-exception-hierarchy/">default error for the <em>rescue</em> block</a>, which is the <em>StandardError</em>, and call the <em>handle_error</em> method with the risen object.</p><p>Inside this method we just do the mapping of the risen error to what we have server responses prepared to. If none of them matches, we fall back to our <em>Errors::StandardError</em> object so the client always gets the nice error message in the server response.</p><p>We can also add extra notifiers for any error that is not mapped in the handler module, so application admins will be able to track the unexpected results.</p><h3>Rising errors in the application</h3><p>In Driggl we managed to create a unified solution for the whole error handling across our API application. This way we can raise our errors in a clean way without repeating any rescue blocks, and our ApplicationController will always handle that properly.</p><pre>def show <br>  Article.find!(params[:id]) <br>end</pre><p>or</p><pre>def authorize! <br>  raise Errors::Unauthorized unless current_user <br>end</pre><h3>Handling validation errors</h3><p>Well, that is a nice solution, but there is one thing we intentionally omitted so far and it is:<strong> validation failure.</strong></p><p>The problem with validations is that we can’t write the error object for invalid request just as we did for the rest, because:</p><ul><li>the failure message differs based on the object type and based on attributes that are invalid</li><li>one JSON response can have multiple errors in the returned array.</li></ul><p>This requires us to add one more error, named Invalid, which is an extended version of what we had before.</p><pre># app/lib/errors/invalid.rb </pre><pre>module Errors <br>  class Invalid &lt; Errors::StandardError <br>    def initialize(errors: {}) <br>      @errors = errors @status = 422 <br>      @title = &quot;Unprocessable Entity&quot; <br>    end <br>    <br>    def serializable_hash <br>      errors.reduce([]) do |r, (att, msg)| <br>        r &lt;&lt; { <br>          status: status, <br>          title: title, <br>          detail: msg, <br>          source: { pointer: &quot;/data/attributes/#{att}&quot; } <br>        } <br>      end <br>    end <br>    <br>    private </pre><pre>    attr_reader :errors <br>  end <br>end</pre><p>You can see that the main difference here is the serialized_hash an initialize method. The initialize method allows us to pass error messages hash into our error object, so then we can properly serialize the error for every single attribute and a corresponding message.</p><p>Our ErrorSerializer should handle that out of the box, returning:</p><pre># json response </pre><pre>{ <br>  &quot;errors&quot;: [ <br>    { <br>      &quot;status&quot;: 422, <br>      &quot;title&quot;: &quot;Unprocessable entity&quot;,<br>      &quot;detail&quot;: &quot;Can&#39;t be blank&quot;, <br>      &quot;source&quot;: { <br>        &quot;pointer&quot;: &quot;/data/attributes/title&quot; <br>      } <br>    },<br>    { <br>      &quot;status&quot;: 422, <br>      &quot;title&quot;: &quot;Unprocessable entity&quot;, <br>      &quot;detail&quot;: &quot;Can&#39;t be blank&quot;, <br>      &quot;source&quot;: { &quot;pointer&quot;: &quot;/data/attributes/content&quot; } <br>    } <br>  ] <br>}</pre><p>The last thing, however, is to rise it somewhere, so the handler will get the exact error data to proceed.</p><p>In the architecture we have, it’s a not big deal. It would be annoying if we would go with updating and creating objects like this:</p><pre># app/controllers/articles_controller.rb </pre><pre>class ArticlesController &lt; ApplicationController <br>  def create <br>    article = Article.new(article_params) <br>    article.save! <br>  end </pre><pre>  private <br> <br>  def article_attributes <br>    params.permit(:title) <br>  end <br>end</pre><p>As this would force us to rescue the <em>ActiveRecord::RecordInvalid</em> error in every action, and instantiate our custom error object there like this:</p><pre>def create <br>  article = Article.new(article_params) <br>  article.save! <br>rescue ActiveRecord::RecordInvalid<br>  raise Errors::Invalid.new(article.errors.to_h) <br>end</pre><p>Which again would end up repeating a lot of rescue blocks across the application.</p><p>In Driggl however, we do take advantage of <a href="https://driggl.com/blog/a/cars-api-endpoints-in-rails-applications">more variety of building-blocks</a>, with validators and transactions, which allows us to easily unify every controller action in the system.</p><pre># app/controllers/articles_controller.rb </pre><pre>class ArticlesController &lt; ApplicationController <br>  def create <br>    process_operation!(Admin::Article::Operation::Create) <br>  end </pre><pre>  def update <br>    process_operation!(Admin::Article::Operation::Update) <br>  end<br>end</pre><p>I won’t go into details of that in this article, but the point is that we could handle the validation errors once inside of the process_operation! method definition and everything works like a charm across the whole app, keeping things still nice and DRY</p><pre># app/controllers/application_controller.rb </pre><pre>class ApplicationController &lt; ActionController::API </pre><pre>  private </pre><pre>  def process_operation!(klass) <br>    result = klass.(serialized_params) <br>    return render_success if result.success? <br>  <br>    raise Errors::Invalid.new(result[&#39;contract.default&#39;].errors.to_h) <br>  end </pre><pre>  def serialized_params <br>    data = params[:data].merge(id: params[:id]) <br>    data.reverse_merge(id: data[:id]) <br>  end </pre><pre>  def render_success <br>    render json: serializer.new(result[&#39;model&#39;]), status: success_http_status <br>  end </pre><pre>  def success_http_status <br>    return 201 if params[:action] == &#39;create&#39; <br>    return 204 if params[:action] == &#39;destroy&#39; <br>    return 200 <br>  end <br>end</pre><h3>Summary</h3><p>You could think it’s a lot of code, but really, for big applications, it’s just nothing comparing to repeating it in hundred of controllers and other files. In this form, we managed to unify all our errors across the whole API application and we don’t need to worry anymore about unexpected failures delivering to the client.</p><p>I hope this will be useful for you too, and<strong> if you’ll find any improvements to this approach, don’t hesitate to let me know in the comments!</strong></p><h4><em>Originally published at </em><a href="https://driggl.com/blog/a/handling-exceptions-in-rails-applications"><em>https://driggl.com</em></a><em>.</em></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b276efa7e796" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>