Wednesday, April 14, 2010

System error support in C++0x - part 5

[ part 1, part 2, part 3, part 4 ]

Creating your own error conditions

User-extensibility in the <system_error> facility is not limited to error codes: error_condition permits the same customisation.

Why create custom error conditions?

To answer this question, let's revisit the distinction between error_code and error_condition:

  • class error_code - represents a specific error value returned by an operation (such as a system call).
  • class error_condition - something that you want to test for and, potentially, react to in your code.

This suggests some use cases for custom error conditions:

  • Abstraction of OS-specific errors.

    Let's say you're writing a portable wrapper around getaddrinfo(). Two interesting error conditions are the tentative "the name does not resolve at this time, try again later", and the authoritative "the name does not resolve". The getaddrinfo() function reports these errors as follows:

    • On POSIX platforms, the errors are EAI_AGAIN and EAI_NONAME, respectively. The error values are in a distinct "namespace" to errno values. This means you will have to implement a new error_category to capture the errors.
    • On Windows, the errors are WSAEAI_AGAIN and WSAEAI_NONAME. Although the names are similar to the POSIX errors, they share the GetLastError "namespace". Consequently, you may want to reuse std::system_category() to capture and represent getaddrinfo() errors on this platform.

    To avoid discarding information, you want to preserve the original OS-specific error code while providing two error conditions (called name_not_found_try_again and name_not_found, say) that API users can test against.

  • Giving context-specific meaning to generic error codes.

    Most POSIX system calls use errno to report errors. Rather than define new errors for each function, the same errors are reused and you may have to look at the corresponding man page to determine the meaning. If you implement your own abstractions on top of these system calls, this context is lost to the user.

    For example, say you want to implement a simple database where each entry is stored in a separate flat file. When you try to read an entry, the database calls open() to access the file. This function sets errno to ENOENT if the file does not exist.

    As the database's storage mechanism is abstracted from the user, it could be surprising to ask them to test for no_such_file_or_directory. Instead, you can create your own context-specific error condition, no_such_entry, which is equivalent to ENOENT.

  • Testing for a set of related errors.

    As your codebase grows, you might find the same set of errors are checked again and again. Perhaps you need to respond to low system resources:

    • not_enough_memory
    • resource_unavailable_try_again
    • too_many_files_open
    • too_many_files_open_in_system
    • ...

    in several places, but the subsequent action differs at each point of use. This shows that there is a more general condition, "the system resources are low", that you want to test for and react to in your code.

    A custom error condition, low_system_resources, can be defined so that its equivalence is based on a combination of other error conditions. This allows you to write each test as:

    if (ec == low_system_resources)
    ...

    and so eliminate the repetition of individual tests.

The definition of custom error conditions is similar to the method for error_codes, as you will see in the steps below.

Step 1: define the error values

You need to create an enum for the error values, similar to std::errc:

enum class api_error
{
low_system_resources = 1,
...
name_not_found,
...
no_such_entry
};

The actual values you use are not important, but you must ensure that they are distinct and non-zero.

Step 2: define an error_category class

An error_condition object consists of both an error value and a category. To create a new category, you must derive a class from error_category:

class api_category_impl
: public std::error_category
{
public:
virtual const char* name() const;
virtual std::string message(int ev) const;
virtual bool equivalent(
const std::error_code& code,
int condition) const;
};

Step 3: give the category a human-readable name

The error_category::name() virtual function must return a string identifying the category:

const char* api_category_impl::name() const
{
return "api";
}

Step 4: convert error conditions to strings

The error_category::message() function converts an error value into a string that describes the error:

std::string api_category_impl::message(int ev) const
{
switch (ev)
{
case api_error::low_system_resources:
return "Low system resources";
...
}
}

However, depending on your use case, it may be unlikely that you'll ever call error_condition::message(). In that case, you can take a shortcut and simply write:

std::string api_category_impl::message(int ev) const
{
return "api error";
}

Step 5: implement error equivalence

The error_category::equivalent() virtual function is used to define equivalence between error codes and conditions. In fact, there are two overloads of the error_category::equivalent() function. The first:

virtual bool equivalent(int code,
const error_condition& condition) const;

is used to establish equivalence between error_codes in the current category with arbitrary error_conditions. The second overload:

virtual bool equivalent(
const error_code& code,
int condition) const;

defines equivalence between error_conditions in the current category with error_codes from any category. Since you are creating custom error conditions, it is the second overload that you must override.

Defining equivalence is simple: return true if you want an error_code to be equivalent to your condition, otherwise return false.

If your intent is to abstract OS-specific errors, you might implement error_category::equivalent() like this:

bool api_category_impl::equivalent(
const std::error_code& code,
int condition) const
{
switch (condition)
{
...
case api_error::name_not_found:
#if defined(_WIN32)
return code == std::error_code(
WSAEAI_NONAME, system_category());
#else
return code = std::error_code(
EAI_NONAME, getaddrinfo_category());
#endif
...
default:
return false;
}
}

(Obviously getaddrinfo_category() needs to be defined somewhere too.)

The tests can be as complex as you like, and can even reuse other error_condition constants. You may want to do this if you're creating a context-specific error condition, or testing for a set of related errors:

bool api_category_impl::equivalent(
const std::error_code& code,
int condition) const
{
switch (condition)
{
case api_error::low_system_resources:
return code == std::errc::not_enough_memory
|| code == std::errc::resource_unavailable_try_again
|| code == std::errc::too_many_files_open
|| code == std::errc::too_many_files_open_in_system;
...
case api_error::no_such_entry:
return code == std::errc::no_such_file_or_directory;
default:
return false;
}
}

Step 6: uniquely identify the category

You should provide a function to return a reference to a category object:

const std::error_category& api_category();

such that it always returns a reference to the same object. As with custom error codes, you can use a global:

api_category_impl api_category_instance;

const std::error_category& api_category()
{
return api_category_instance;
}

or you can make use of C++0x's thread-safe static variables:

const std::error_category& api_category()
{
static api_category_impl instance;
return instance;
}

Step 7: construct an error_condition from the enum

The <system_error> implementation requires a function called make_error_condition() to associate an error value with a category:

std::error_condition make_error_condition(api_error e)
{
return std::error_condition(
static_cast<int>(e),
api_category());
}

For completeness, you should also provide the equivalent function for construction of an error_code. I'll leave that as an exercise for the reader.

Step 8: register for implicit conversion to error_condition

Finally, for the api_error enumerators to be usable as error_condition constants, enable the conversion constructor using the is_error_condition_enum type trait:

namespace std
{
template <>
struct is_error_condition_enum<api_error>
: public true_type {};
}

Using the error conditions

The api_error enumerators can now be used as error_condition constants, just as you may use those defined in std::errc:

std::error_code ec;
load_resource("http://some/url", ec);
if (ec == api_error::low_system_resources)
...

As I've said several times before, the original error code is retained and no information is lost. It doesn't matter whether that error code came from the operating system or from an HTTP library with its own error category. Your custom error conditions can work equally well with either.

Next, in what will probably be the final instalment, I'll discuss how to design APIs that use the <system_error> facility.

113 comments:

Anonymous said...

Hi Chris, thanks for this serie of articles!

This was really helpfull!

Great blog! Nice and impresive work!

Thanks, I've learned so many things about asynchronous thinking and programming!

What about URDL :)? This seems to be a great an usefull application of ASIO. And what about your book? ;)

Once again : thanks for your work! Very helpfull.

towi said...

Your blog series is amazing! Please, continue :-)

Unknown said...

Hi Chris, great series, I was looking forward to the API entry. This is a great intro.

Unknown said...

Hi Chris. Playing with clang I came across an error ? It seems related to something that crept into the standard late. This affects the steps involving 'defining and declaring' non user defined types in std::.

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

Unknown said...

I just came across this, this also causes asio to fail as it uses signals2 and there is a problem with forward declarations. This is fixed in boost svn though.

http://stackoverflow.com/questions/9576112/implicit-instantiation-of-undefined-template-boost-bug-or-clang-bug

Logan Chien said...

It seems that there is a minor typo in the getaddrinfo_category example: the assignment operator should be replaced by equality comparison operator.

BEFORE:

return code = std::error_code(
EAI_NONAME, getaddrinfo_category());

AFTER:

return code == std::error_code(
EAI_NONAME, getaddrinfo_category());

Unknown said...

Learn Easy C Programming Tutorials.

Unknown said...

Hi Chris, please finish the series! We are still waiting.

Anonymous said...

Do you have the complete working code for this?

Rui Pacheco said...

How would std::error_code handle an error that includes not just an error code but also a message from the remote system?

Jack Norman said...

Thanks for the great article! If you are in search of a great software development company, check Softvelopers. Company has 17+ years of field experience in software development.

Chris Winslow said...

That is a really good article. I would like to add that sometimes if you want to get a proper product done it is better to contact a software development company with high proficiency in this. I would recommend the EffectiveSoftcompany.

Mariya said...

Thanks for sharing such information! It may come to your mind that it's better to turn a software development company...then
iTechArt will help you I guess. At least their expertise is a match.

DBJDBJ said...

Does anybody mind, if I ask? Where is the next post, on "how to design API's" to use this?

Ada Smith said...

Wow cool who does not know this site safe online casino ratings that half of life does not know on this site you can really earn money without blessing

Sergey said...

Hire php developers – Save cost by hiring dedicated PHP developers & PHP programmer from this site.

Siva said...

The blog you have shared is incredibly helpful. The tips you have shared related to web development is really informative. Thanks for sharing this blog!
Hire Dedicated Opencart Developers
Hire Dedicated Magento Developer
Hire Dedicated Web Developers
Hire Dedicated Developers
Hire Cake Php Developer

Sekar said...

In the competitive market finding the best outsourcing services is a challenging task. This post helps me to find the best one. Thanks for sharing this post.
Hire a Programmer
Mobile App Development India
Hire Wordpress Developer
Hire Opencart Developer
Hire Php Programmer

bestjobsinbhubaneswar said...

Superb post by the author.
Web Design

Tyler Worgan said...

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..

tree trimmers palm beach county

Tyler Worgan said...

Thanks for sharing a very nice article
stamped concrete minneapolis

Tyler Worgan said...

I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers
fire restoration services broward county

Tyler Worgan said...

Hi, This is nice article you shared great information i have read it thanks for giving such a wonderful Blog for reader.
water heater installation minneapolis

Gerald Force said...

Excellent Post! Los angeles employment lawyer

Tyler Worgan said...

This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest posts
fire restoration companies fort lauderdale

Tyler Worgan said...

I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers.
remodeling contractors clearfield ut

Tyler Worgan said...

Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
stamped concrete driveway fort lauderdale

haroonullah said...

Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
Haroon Ullah

Trade Stock said...

Thanks for sharing the great article on this topic.
Jonathan Dax Cooke

Tyler Worgan said...

Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
bathroom remodeling ogden ut

Tyler Worgan said...

Great article and a nice way to promote online. I’m satisfied with the information that you provided
concrete stamping company broward county

Shop Sous Vide said...

I like this post.
emergency tree services tequesta

Clark said...

Brilliant .i love it reading.
patio screen repair port st lucie

Clark said...

Nice post.
tile reglazing west palm beach

Clark said...

Nice post.
tile reglazing west palm beach

Clark said...

Wonderful post shared.
bathtub refinishing and fiberglass expert fort lauderdale

Shop Sous Vide said...

Amazing post shared. fiberglass bathtub refinishing west palm beach

Shop Sous Vide said...

I really inspired from this post.

ac repair west palm beach fl

maya said...

interesting way of explanation .
hotels in Karachi

maya said...

Thanks! keep rocking.
123movies

The Gabay Group said...

הייתי חייבת לפרגן, תודה על השיתוף.
חברת קבוצת גבאי

Unknown said...

Nice post.

גדרות אלומיניום

Cinema furniture said...
This comment has been removed by the author.
Unknown said...

Thanks for a wonderful share.
123movies

Petersons said...

Thanks for the great article!
123movies

Aleena said...

סופסוף מישהו שתואם לדעותיי בנושא. תודה.
תכשיטי אפולו

Dafmatok Hosting Trays said...

מזל שנתקלתי בכתבה הזאת. בדיוק בזמן
מגשי אירוח

Cinema furniture said...

הייתי חייבת לפרגן, תודה על השיתוף.
שולחן עגול נפתח

Comfi furniture said...

כתיבה מעולה, אהבתי. אשתף עם העוקבים שלי.
רהיטים לסלון

Amediciercosmetic said...

תמשיכו בפרסום פוסטים מעניינים כמו זה. תודה.
טיפול קוסמטי לפנים

Unknown said...

great post.

סראונד סאונד

Planner Productions said...

כל מילה. תודה על השיתוף, מחכה לעוד פוסטים בנושא.
אטרקציות לחתונות

Helena Merry said...

go123movies
Best free streaming movies sites: Movies are the great entertainment part of our life. Not just for entertainment purposes also it influences our living greatly. Yes, there are millions of good movies to watch in our free time with family and friends. Besides watching movies on TV and at the theaters, watch free streaming movies online from free movie sites have become popular.

brokertome said...

מעולה. תודה על הכתיבה היצירתית.
ברוקרים

Unknown said...

thanks for sharing.
123 movie

Unknown said...

Great work keep it up.

123movies

gemcreature said...

Great Information,it has lot for stuff which is informative.I will share the post with my friend
playboy bunny necklace

Unknown said...

keep posting very nice.

סייטלינקס

delight girls said...

The best way to spend your night in 31 Dec with Hong Kong Escorts Girls, call us for bookings

Bloxi said...

אין ספק שהפוסט הזה דורש שיתוף. תודה.
הדפסה על עץ

lajwantidevi said...

vidmate

Reputation management said...

כל מילה. תודה על השיתוף, מחכה לעוד פוסטים בנושא.
ניהול מוניטין ברשת

sdf said...

Lottery Sambad Today Result 11:55 AM, 4PM,8PM
Lottery Sambad Today Result

Anonymous said...

Thanks for sharing this nice informatione!
financial modelling to give you confidence in your financial strategy and provide business valuations.

delight girls said...

Want sexy and hot moments in popular Hong Kong Escort, Give your life lovely time, Want more fun with escort girls.

Anonymous said...

Download your favorite Latest Mp3 Lyrics which are available in English, Hindi, Bangla, Telugu, Latin, Arabic, Russian, etc.

Click Here

Click Here

Click Here

Click Here

Click Here

wewin55 said...

Wow! Very informative blog. I visits lots of blog but this blog is very unique. Thanks
CMD368

Plaisio said...

Thanks for the information. This is a very informative post. Plaisio Computer SA provide a stock quote, history, news and other vital information to help you with your stock trading. It is a Greece-based company that assembles and trades personal computers telecommunication.

Daily Image Funda said...

Wonderful share by the author. I found this blog helps me a lot.
Good Night Romantic images

Unknown said...

Superbly written article
global asset management korea

Anonymous said...

Thanks for your sharing! The information your share is very useful to me and many people are looking for them just like me!


We have collection of best 2020 sex doll to fulfill your desire, so if you need realistic female sex dolls then Love Doll Palace is largest online store for you , who are providing young love doll for you, these are made by silicone and TPE, which will give you full happiness at sex duration and you can enjoy with her at any position.

Anonymous said...

Choose the right lawyer to defend you. The New York Criminal Defense Attorneys at Abe George Lawyer Law Group handle different types of crimes in NewYork. So if you need then abe george lawyer is one of the best for you!!

Abe George and Lawyer

Abe George and Lawyer

Abe George and Lawyer
Abe George Lawyer
Abe George Lawyer
Abe George and Lawyer
Abe George and Lawyer

Sitelinx said...

כל מילה. תודה על השיתוף, מחכה לעוד פוסטים בנושא.
חברת קידום אתרים

Anonymous said...


Meet Abe George Lawyer recognized as the best criminal defense attorney to protect your rights and handles entire crucial situations of yours and your family.
He is a highly experienced executor, who serves the excellent defendant assistances with his potential methodology to come you out from the crime obligations
efficiently.
abe george lawyer
abe george lawyer
abe george lawyer

Unknown said...

כתיבה מעולה, אהבתי. אשתף עם העוקבים שלי.
מזרון למיטת תינוק

Unknown said...

כל מילה. תודה על השיתוף, מחכה לעוד פוסטים בנושא.
גיוס כסף לסטארט אפ

Anonymous said...


Thanks For Sharing this Information!!
If you are getting issue login to orbi Router. Then use www.orbilogin.net. It enables the user to connect to orbi device with
ease.

Dogma said...

פוסט נחמד. חייב לשתף עם העוקבים שלי.
עיצוב ממשק משתמש

Ignou projects said...

Thanks for sharing

Ignou MA education project

dev said...


Hi! I really like your content. Your post is really informative. I have learned a lot from your article and I’m looking forward to apply it.
ignou assignment 2019 ba
ignou ba assignment
ignou assignment 2020
ignou assignment december 2019





Hie I really like your content. Your post is really informative & geneunie.Thank for sharing such a good information really it.
ignou solved assignment
ignou assignment 2019
ignou solved assignment 2019
Ignou mba finance project








Hi! I really like your content. Your post is really informative. I have learned a lot from your article and I’m looking forward to apply it.
ignou solved assignment 2020
bhdf 101
ignou assignment solved 2019





This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your magnificent post. Also, I’ve shared your website in my social networks.
ignou assignment solved 2019
ignou mcom assignment
ignou assignment 2019 solved













This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your magnificent post. Also, I’ve shared your website in my social networks.
ignou assignment 2019 ba
ignou ba assignment
ignou solved assignment free





dev said...

Fantastic piece, well tailored…. You sort of cleared my phobias… Now I can give it a shot… I pray I don’t run out of contents!…a big kudos

gyn services brooklyn
smp seattle
bathroom remodel near me
hvac near me
vinyl siding repair near me
wedding dj columbia sc

How To Asset Manage said...

great post.
global asset management

Global Asset Management Udemy said...

Wow cool
global asset management korea

Priya said...

What a Beautiful post! This is so chock full of useful information I can't wait to dig and start using my time on blogging. I am just over six month into blogging , I newly wrote an article Best Immune Booster Fitspire product makes immune stronger & healthier to fight against corona.

dev said...

Fantastic piece, well tailored…. You sort of cleared my phobias… Now I can give it a shot… I pray I don’t run out of contents!…a big kudos

gyn services brooklyn
smp seattle
bathroom remodel near me
hvac near me
vinyl siding repairin summerville sc
wedding dj columbia sc

routerlogin.net said...

Get the support for www.routerlogin.net routers, extenders, modems, and cameras and other popular devices manufactured by the Netgear.

Coding P said...

Never experienced this error before, I will get solution form Los Angeles Wordpress Developer

udita sharma said...

Loveed it your cash app refund every single post

sheikh said...

Hire any of these c++ development companies I am sure they be able to sort this c++ error for you. All the companies listed have top c++ developers.

사설토토 said...

סגנון כתיבה מרענן, תודה על השיתוף.
הדפסה על קנבס

Clark said...

great.
מצלמות במעגל סגור

luckky said...

your artical is very great i regularly visit your website you can also visist my website my website url is https://letestnews.co.in/


letestnews

intercom4u said...

This is a great article thanks for sharing this informative information.
אינטרקום לדלת כניסה

Unboxthedigital said...

Great sitee and great experience you have this article is damn cool Column pipe manufacturer really and i bookmarked your page also......

Clark said...

nice post.
global asset management

Fixadoor said...

Great Information
Garage door repair

Clark said...

nice post.
Global asset management Korea

Stratford Management said...

thanks for share the valuable knowledge
stratford management Tokyo

Petersons said...

what a great style, it not easy job well don.


Bastion Balance Seoul

Petersons said...

Congratulations you guys, nice couple, have fun.


Investors Magazine

ibglobalacademy said...

I have a project that I'm simply now working on, and I have been at the
glance out for such information
IB Global Academy

orbilgoin said...

For technical support https://orbilogiinn.com/ login Visit our site and get the 24*7 technical support from us.
Helpline no. 9177320091

Garage Door Pros Ontario said...

Thanks for sharing the useful information.
Garage Door Repair Orleans

dextertex said...

I found your blog very informative and really well written. otsakre for your good effort you've put in. Visit me for Router tech support. 24/7 Chat Assistance for complex Routers issues. Call me for Assistance 9177320091 Visit me for making good relations. Thanks.
http://orbiloginn.com
https://www.linksysmarrtwifi.com
https://myarloo.com/ http://www.routersynologyy.com https://routerloglogin.com

Orbi Login
Arlo Login
Linksyssmartwifi com
find Synology
Routerlogin

Petersons said...

מרתק כמה שלא הבנתי כלום עד שקראתי את המאמר הנפלא הזה

בניית בריכת שחייה מבטון

Overhead Door Pros said...

I really like your blog. Great article.
overhead door repair Calgary

Selectmytutor said...

This unique blog is no doubt cool additionally informative. I have discovered a lot of interesting advices out of this amazing blog. I ad love to return over and over again. Thanks a bunch!
Primary School Tutor

Petersons said...

Great lovely arrangements looks traditional wedding.


Garage Door Repair Calgary

Garage Door Pros Ontario said...

Nice ideas shared.

Garage Door Repair Cranberry

networkengineer said...

I am a Staff Author at FieldEngineer.com a Marketplace for On-Demand telecom workforce, extending from field engineers to high-level network engineers, project managers and Network Architects in 146 nation

Soa security

euro cars said...

מעניין מאוד, למרות שלא הכל מדויק לדעתי
רכב במימון מלא ללא מקדמה

euro cars said...

תודה על השיתוף, מאוד מעניין
עקירה כירורגית

euro cars said...

חשבתי שאתקל בסתם עוד מאמר שטחי. טעיתי.
שמות כלבים