Error Helpers in C

I’ve been writing a lot of C lately for a game I am working on. I am not a perfect programmer and I would like to catch my bugs before they arise. Thus, I am attempting to learn Rust in my free time.


Printing a backtrace in C is not incredibly difficult to accomplish. Although the following is fairly primitive, it will aid in your ability to discern what is happening in your program

/// @file core/backtrace.c
#include <execinfo.h>
#include "backtrace.h"

/// @brief Prints a backtrace of up to the last 256 calls
/// @param [out] fd The file descriptor ID to write to
void print_backtrace(int fd) {
    void* array[256];
    size_t size = backtrace(array, 256);
    backtrace_symbols_fd(array, size, fd);

The output will look like the following


As you can see, in a method test_block_insertion I call print_backtrace. This is incredibly helpful if you need to determine how deep in the program your issue occurred.


I’ve been tinkering with Rust in my free time to get a better understanding of it and I have come to enjoy the panic! macro it employs. I like the verb and decided that it would work perfectly in my daily use.

With some alterations, I just wanted panic to do exactly what its name suggests, I want the program to panic with a message and abort.

/// @file core/panic.h
#pragma once

#include <stdlib.h>
#include <stdio.h>
#include "backtrace.h"

#ifdef NDEBUG
#define panic(message)
/// @brief Causes the program to abort and print a message
/// @param [in] message The error message you wish to spit out to stderr.
#define panic(message)                                               \
    do {                                                             \
        fprintf(stderr, "panicked at: %s:%d\n", __FILE__, __LINE__); \
        fprintf(stderr, "--> %s %s\n", message);                     \
        fprintf(stderr, "--> STACKTRACE START\n");                   \
        print_backtrace(2);                                          \
        fprintf(stderr, "--> STACKTRACE END\n");                     \
        fflush(stderr);                                              \
        abort();                                                     \
    } while (0)

Example usage would be like this

int some_function(uint8_t* data, size_t length) {
  if (length == 0) {
    panic("Zero length buffer provided!");

  // consume data

  return 1;

Output from this macro will look like the following.

panicked at: /home/warmwaffles/code/example/rbp_test.c:173
--> message: Failed to insert the block correctly
Aborted (core dumped)

I wanted the core dump to take place so that I can inspect it if I need to. Luck favors the prepared, and I always like to be prepared.


I use assert(expr) liberally through out my code to ensure that my program operates as I intend it to. Sometimes I make a mistake and would like to be notified where it happened and how deep in the call stack it did.

Unfortunately vanilla assert(expr) does not do this. But it is a simple enough macro to override and provide a little more meta information about where it failed and why.

/// @file core/assert.h
#pragma once

#include <stdlib.h>
#include <stdio.h>
#include "backtrace.h"

#ifdef NDEBUG
#define assert(expr)
#define assert(expr)                                                                     \
    if(!(expr)) {                                                                        \
        fprintf(stderr, "assertion (%s) failed at: %s:%d\n", #expr, __FILE__, __LINE__); \
        fprintf(stderr, "--> STACKTRACE START\n");                                       \
        print_backtrace(2);                                                              \
        fprintf(stderr, "--> STACKTRACE END\n");                                         \
        fflush(stderr);                                                                  \
        abort();                                                                         \

As you can see it looks almost exactly the same as panic(message) does. However, I want the expression to be spit out into stderr so that I can see what expression failed.

assertion (1 == 0) failed at: /home/warmwaffles/code/example.c:170
Aborted (core dumped)

Found these little bits of code to be useful, and figured others would probably find it useful as well.

Ruby Mixins

Mixins are a bit of a touchy spot for me. I am in a love hate relationship when it comes to them. In some cases, they work brilliantly and in other cases they hide complexity.

I have a few rules that I try to follow when I am considering using mixins.

  1. Does it hide complexity / indirection?
  2. Will it benefit the code base to share code?
  3. Will it override methods or will methods need to be overriden?

Moving methods into mixins to just move them is not sufficient enough to warrant the need for mixins. It is something that should be used to refactor once a pattern is established. Mixins should only be used for adding abilities to classes.

Let’s take a look at an example. We need an ability to revoke tokens mixed into three separate classes.

module Revokable
  # Sets when the token was revoked
  # @return [void]
  def revoke
    @revoked_at =

  # Check to see if the token was revoked
  # @return [TrueClass,FalseClass]
  def revoked?

The personal token represents a token that belongs to a user and never expires, but it can be revoked.

class PersonalToken
  include Revokable

  attr_accessor :id, :token, :user_id

The access token represents a token that is only available for a limited time.

class AccessToken
  include Revokable

  attr_accessor :id, :token, :user_id, :refresh_token_id

  def expire
    @expired_at =

  def expired?

The refresh token never expires but is only used for getting another access token.

class RefreshToken
  include Revokable

  attr_accessor :id, :token, :user_id

We have accomplished is adding an ability to three classes without hiding a lot of complexity. If you find that your classes have too many methods defined, that should be a sign that it is too complex. But, do not immediately reach for mixins just because it makes the class less cluttered. It actually hides the mess as opposed to solving the issue.

Use mixins wisely!

A Ruby Yukata

Let me introduce you to my new library called Yukata. It is a light weight Ruby attribute library that is configurable and extendable.

Virtus has been a huge inspiration for this library. I enjoyed the DSL it offered, while allowing me to have a quick way to make data objects.

Here is an example on how to utilize Yukata:

class Person < Yukata::Base
  attribute :first_name, String
  attribute :last_name,  String
  attribute :born_on,    DateTime
  attribute :married,    Boolean, default: -> { false }

The #attribute method is straight forward with its meaning. It is dynamically creating both getter and setter methods for the object. It can be thought of as a fancy attr_accessor but with a few extra features. It provides a fast way to discover what data type can be expected for that attribute.

Example Usage

When using Yukata, the the initializer expects a hash to be provided or a class that behaves like a Hash.

john ={
  :first_name => 'John',
  'last_name' => 'Doe',
  :born_on => '1969-01-16T00:00:00+00:00'

Yukata will take the hash and assign the values to their respective attribute keys. If a setter method is defined, then a corresponding value can be passed as well.

class Foo < Yukata::Base
  attr_accessor :bar
  attribute :qux, String
  attribute :baz, String, writer: false

  def baz=(value)
    @baz = value.to_s

foo ={
  bar: 'woot',
  qux: 'herp',
  baz: 'derp'
}) # => 'woot'
foo.qux # => 'herp'
foo.bas # => 'derp'
foo.attributes # => { bar: 'woot', qux: 'herp' }

If a :coerce => false is passed, then Yukata will not attempt to coerce that attribute and leave it as is. This can be handy if a custom coercion is desired for the specific model. Here is an example:

class Episode < Yukata::Base
  attribute :season, Integer
  attribute :number, Integer
  attribute :name,   String, coerce: false

  # @override overides the yukata definition
  def name=(value)
    @name = '%sx%s - %s' % [@season, @number, value]

episode ={ season: 1, number: 1 }) = 'Foo Bar' # => '1x1 - Foo Bar'

Now, remember just because there is access directly to instance variables does not mean it is okay to abuse them. With great power comes great responsibility, this means I am not responsible for your mistakes.

Setting Attribute Defaults

Sometimes the objects need default values if it is not set. Defaults are lazily loaded. They will only be set once the getter method is called.

class Book < Yukata::Base
  attribute :name,       String
  attribute :created_at, DateTime, default: -> { }

Registering Custom Coercions

This library only comes with basic coercers. I tried to make as little assumptions about the data coming in as I could. I believe that the consumer of the library should be the one who defines the coercions.

If the value can not be coerced, it is simply passed through and left alone.

Yukata.coercer.register(String, Array) do |string, target|
  string.split(' ')

Optional Readers and Writers

When declaring an attribute, both the reader and writer can be skipped. There is a use case where this would be handy.

class Book < Yukata::Base
  attribute :title, String, writer: false, reader: false

  def title=(value)
    @title = value.to_s

  def title

This is a bit contrived, but it demonstrates the following:

  1. The expected return data type for #title is a String.
  2. Custom coercer is defined.
  3. The attribute will be included when #attributes is called on Book.

If :writer => false is provided, there would be no need to include :coerce => false since the coercion only takes place when the value is being set on the object.


I wrote this library becaues I wanted to see how Virtus accomplished this task and how I could go about doing it differently. This is a highly configurable library that can be used to put your fat models on a diet.


Responding With Errors in Rails

As I work on API projects I find myself having to track down status codes and ensuring a consistent response code for any given error. Keeping these status codes consistent throughout the application starts to become a hassle.

A solution that I stumbled upon happened to be something very simple.

# /lib/errors/unauthorized_access_error.rb
module Errors
  class UnauthorizedAccessError
    def status

    def message
      'unauthorized access'

    def to_hash
        meta: {
          code: status,
          message: message

    def to_json(*)

In my controller I would do the following:

class API::V1::UsersController < API::V1::ApplicationController
  before_filter :authorize!

  def index
    render(json: account.users)
  rescue Errors::UnauthorizedAccessError => error
    render(json: error, status: error.status)

Very simple, and very elegant. The status code travels with the UnauthorizedAccessError class and is very well self documenting. This is a very simple example however, the principle still remains that the errors themselves carry the burden of what the HTTP response codes should be and what the response should look like.

It could get a little tedious to keep rescuing from that one error every method, fortunately Rails comes with a rescue_from and you can use that to blanket your application.

class API::V1::ApplicationController
  rescue_from Errors::UnauthorizedAccessError, with: :render_error

  def render_error(error)
    render(json: error, status: error.status)

# Your other controller would then look like this!
class API::V1::UsersController < API::V1::ApplicationController
  before_filter :authorize!

  def index
    render(json: account.users)

You could even take this a step further and make all of your error classes decend from a common parent like Errors::Error and then do the following:

class API::V1::ApplicationController
  rescue_from Errors::Error, with: :render_error

  def render_error(error)
    render(json: error, status: error.status)

The possibilities are endless, but the benefits are huge. Keep things simple and you’ll enjoy the new found power.

Test Spies

Test spies are a wonderful tool to utilize in the RSpec testing environment. When used in moderation and with care. Test spies require that a called method be stubbed so that it can be checked to see how it was invoked.

I have put together a really simple class to demonstrate a test spy.

class NotifyUser
  attr_reader :user

  def initialize(user)
    @user = user

  def execute(params={})
    mailer.notify({ message: params[:message] })

  def mailer

Notice in the test below that a test spy follows a pattern. There is a mock up section, an excercise section, and a verification section. Each of these are important and I always put a space in between the sections. It’s much easier to see what is happening in the test.

describe NotifyUser do
  let(:user) { double('User') }
  let(:command) { }

  describe '#execute' do
    it 'sends the notification to the user' do
      # Mock up
      mailer = double('SomeMailer', notify: true)
      command.stub(mailer: mailer)

      # Excercise
      command.execute({message: 'Hello'})

      # Verification
      expect(mailer).to have_received(:notify).with({ message: 'Hello'})

Mocking up outside of the it block should be kept to a minimum. This is because it can get to be a little hectic trying to understand what the test is doing. I like tests that are readable and succinct.

If the length of a test file is forcing me to start mocking outside of it blocks, I like take a step back and ask myself, “Is this class really complex?” It is important to realize when tests are getting more and more difficult to maintain, that the code base is most likely really coupled.

When to use them

Test spies are not meant to be used everywhere. I typically use them when a class is communicating with an external object. I will stub the method that wraps the object and make it return a double. This is so if the code base does change, this test will fail quickly and force the developer to look at what it failed and possibly refactor tests.

Do not apply liberally, but do apply where necessary.