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.

500 comments:

«Oldest   ‹Older   401 – 500 of 500
사설토토 said...

I’m thinking some of my readers might find a bit of this interesting. Do you mind if I post a clip from this and link back? Thanks 사설토토

Marry said...

Download the necessary app, then add the Nest camera to the app by scanning a QR code. If you have any questions during nest camera installation, you can get assistance or visit the website to read the setup guide. You can also trust our technicians on this. They will help you out for the same.
nest camera login

keonhacai said...

keonhacai

Simran said...

thanks for providing such a great article,this article is very help full for me, a lot of thanks sir

Online School Management Software

Beautyglaming said...

Thanks For Sharing Breaking News In Hindi
Thanks for sharing information Rashifal Today News in Hindi

Simran said...

Hi! I really like your content Your post is really informative.

Learning Management System

Integrated Learning Management System

csc said...

This has really made me think and I hope to read more.

SBO222.bet
sbo
sbobet

Ahaana jain said...

Hi! I really like your content. Your post is really informative.

Best Custom Software Development Company
Website Development Company

keonhacai said...

keonhacai

Simran said...

I had no idea what a blog was or how to start one

Campus Learning Management System
LMS System

dipanshu sharma said...

Nice blog post so thanks a lot for sharing this great blog post.. keep more post for sharing.. have a nice day.
Real Estate Lawyer in Canada

Aman Patwal said...

Thanks for Sharing the information
best pte coaching in delhi|ielts exam eligibility

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Best Custom Software Development Company
Top Web Development Companies

Ahaana jain said...

I have learned a lot from your article and I’m looking forward to applying

Internet Marketing Agency

Software Solutions Company

Ahaana jain 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

Customised Software
Top Web Development Companies In USA

Ahaana jain said...

I will definitely use this information in the very near future. I have saved this link and will return in

Best Custom Software Development Company

Best Web Design Company USA

Cari said...

Appreciating the persistence you put into your blog and detailed information you provide. Read: business central for manufacturing

Ahaana jain 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

Features Of E-commerce Website

Top Digital Marketing Companies In 2021

GOSTOPSITE23 said...

HI, I REALLY WANT TO ADMIRED THIS KIND OF POST BECAUSE THIS ARTICLE HAS SO MANY THINGS THAT I WANTED TO KNOW. THANKS!
온라인섯다

TOTOSITEWEB23 said...

HI, GOOD DAY! YOU MADE SUCH AN INTERESTING PIECE TO READ, THIS IS GREAT!
THANKS FOR SHARING THIS!
안전놀이터

GUIDE03 said...

THIS BLOG IS VERY INFORMATIVE AND HELPFUL POST, THIS SO VERY GOOD.
일본야동

TOTOSAFEDB23 said...

HELLO EVERYONE, I REALLY LOVE THIS KIND OF POST , WHILE HAVING I READING THIS I FEEL AMAZING WITH THIS POST, THANKS
안전놀이터

MM Hospital said...

MM Hospital is the Best Multi speciality Hospital in Namakkal.
Located in South India, it has attained an iconic reputation since its inception.

Dijital Pazarlamacilar said...

Reklam Nedir Reklamın Tanımı

Reklam, herhangi bir ürün veya hizmeti tanıtmak veya satmak veya müşteriyle etkileşim kurmak için sponsorlu, kişisel olmayan bir mesaj veya içeriğin kullanılmasını içerir.

Herhangi bir ürün veya hizmetin erişimini, varlığını, olası satışını ve satışını optimize etmede oldukça etkili olan bir pazarlama iletişimi biçimidir. Dürüst bir şekilde reklam verirken işletmelerin özünde olması gerekir.

Amerikalı bir reklam yaratıcı yönetmeni olan William "Bill" Bernbach, reklamcılığın bu faktörünü vurgular ve şöyle der:

“Reklamcılıkta en güçlü unsur gerçektir.”

Bu yazıda, ne olduğunu, nasıl çalıştığını ve reklamcılığın kritik yollarının neler olduğunu anlamak için Reklamcılık dünyasının derinliklerine dalacağız. O halde hemen başlayalım-

İçindekiler
Reklamcılık Nedir?
Reklamcılık, bu terim, 'zihni çevirmek' anlamına gelen Latince 'reklamveren' kelimesinden türetilmiştir.

Reklam bir iletişim yoludur. Ürünler veya hizmetler, fiyat vb. hakkında çok sayıda mesaj taşıyan bir pazarlama aracıdır. Reklam, insanları pazardaki herhangi bir hizmet veya ürün hakkında etkilemek ve bilgilendirmek için kullanılır.

Reklam, TV, radyo, afişler ve gazetelerle bağlantılıdır.

Her türlü iletişim aracı reklamlar için işe yarayabilir. 19. yüzyılda, reklamcılık modeli, sert satış yönünde kesin bir değişiklik gösterdi.

Reklam, ticaret ve ticaretin büyümesiyle bir destek aldı.

Hindistan Reklam Ajansları Birliği (AAAI) 1945'te kuruldu.

Meslek, çıkarlarını ve sorunlarını temsil etme yetkisine sahipse, temsili bir organ olarak tanınmaya başladı.

Ürünlerinin tanıtımı için ödeme takip eden bir taktiktir. Bu promosyon mesajları, reklam olarak da adlandırılır.

Reklam kavramı, çeşitli pazarlama ve tutundurma teknikleri ile hedef pazarın ve müşterilerin satın alma kararlarını ve satın alma davranışlarını etkileme girişimi ve girişimi olarak tanımlanabilir.

Günümüzde markanın , her zaman dinamik ve akıcı olan pazardaki rekabette öne çıkmak için etkili Reklam kampanyalarını seçmesi, tasarlaması ve yürütmesi gerekiyor.

Firmaların yazar kasalarını çaldırabilmeleri ve daha yüksek satış ve yüksek kar hedeflerine ulaşabilmeleri için 360 derecelik bir Reklam ve pazarlama planına sahip olmaları gerekmektedir.

Geleneksel tanıtım yöntemlerini kullanmaktan, günümüzün son modası olan dijital mecraları ve sosyal medya kanallarını tercih etmeye; firmanın optimum ve kapsamlı bir Reklam planına sahip olması gerekir.

AFREEN said...

TurboTax is a software package for preparing US income tax returns produced by Intuit. Click on this link https://sites.google.com/a/taxsoftwarelicense.com/turbotaxmyaccountdownloads/ to know about it.

AFREEN said...

A report has revealed that TurboTax is the largest and most popular tax-preparation software, handling a solid 30% of electronic filings. If you want to know more about this then clickturbotax.ca/download here.

AFREEN said...

TurboTax Online provides the convenience of preparing and e-filing your tax return from virtually any computer or mobile device with Internet access. For more information visit installturbotax.com with license code our website.

AFREEN said...

TurboTax has a filing option that allows you to file your federal return and state return at no cost. If you want to know more about TurboTax, contact install turbotax with license code us via this link.

AFREEN said...

Sign in to the TurboTax account with the license code at installturbotax.com. Click turbotax.ca/download the download arrow next to the product you want to install.

AFREEN said...

TurboTax is a market leader in its product segment, which rivals many tax planning software across the world. For more information visit install turbotax with license code our website.

AFREEN said...

TurboTax is a tax preparation software package developed by the company Intuit. This peculiar Turbotax is extremely popular among users for its intuitive tax preparation structur installturbotax.com with license code software is really helpful for users who are not familiar with tax filing system.

AFREEN said...

To download TurboTax with a license code, enter your activation number in the License Code box on the install turbotax with license code activation screen and select Continue to complete the installation.

AFREEN said...

Turbotax is tax preparation software for tax returns of the United States and Canada. If you want to know more about it click install turbotax with license code here .

AFREEN said...

Your license code is a 16-character combination of letters and numbers that verifies the software and allows you to start using and installing TurboTax.For more details visit our website installturbotax.com with license code installturbotax.com with license code

AFREEN said...

TurboTax Online offers the convenience of preparing and e-filing your tax return from virtually any computer or mobile device with Internet access.Go with our link installturbotax.com with license code to know more visi on installturbotax.com with license code our website

AFREEN said...

TurboTax is a software package for preparing US income tax returns produced by Intuit for more details click the link turbotax.ca/download .To know more visit on website

AFREEN said...

Turbotax is tax preparation software for tax returns of the United States and Canada. If you want to know more about it click turbotax.ca/download here .

AFREEN said...

TurboTax only offers a free version for simple tax returns. It lets you file Form 1040, claiming the earned income tax credit.click turbotax.ca/download this link know about it turbotax.ca/download

AFREEN said...

The maker of TurboTax, one of the companies that has promised the IRS to offer free tax filing to low-income earners.for more visit turbotax.ca/download our websit

AFREEN said...

The maker of TurboTax, one of the companies that has promised the IRS to offer free tax filing to low-income earners.for more visit turbotax.ca/download our websit turbotax.ca/download

AFREEN said...

TurboTax offers an easy-to-use process with helpful interview-style questions and options to get help when you need it, making it a little more expensive than its competitors.If you want toknow more contact turbotax.ca/download us via a link turbotax.ca/download

AFREEN said...

TurboTax has excellent customer service options. You can connect with a customer service representative by phone, email or chat as well as with turbotax.ca/download this link turbotax.ca/download

AFREEN said...

TurboTax is a software package for preparing US income tax returns produced by Intuit. Click on this turbotax.ca/download link to know about it.

Anonymous said...

faststone capture crack
ableton live crack

orbilogin.com said...

This is a great tip especially to those fresh to the blogosphere. Brief but very accurate info… Thank you for sharing this one. A must read post!

orbilogin.net said...

Orbilogin.net is also known as Orbilogin.com. Netgear Orbi Login helps users access broken web connections every moment of each device

orbilogin.com said...

ORBILOGIN.COM is a one stop platform for all your e-hospital needs, the site is developed to provide a complete and hassle free online registration and booking experience. With
orbilogin.com, you can register for, schedule, and pay all your medical tests, scans, and visits to a medical center from one screen. ORBILOGIN.COM is the only E-Health Portal that supports both the desktop and mobile platform.

orbilogin.net said...

Need something better to increase your internet speed? You don't have to worry anymore. Netgear offers you the most powerful Orbi router with several advanced features. This will allow you to easily do the Netgear Orbi login without any hassle. It has high security and parental control which makes browsing safe for your kids. Here you can find more detailed information, such as how to access orbilogin.com or orbilogin.net? You can also learn the setup process with orbilogin.com like the Orbi app. You can then troubleshoot using the troubleshooting steps and update the router's firmware.

orbilogin.net said...

It’s really a great and helpful piece of info.
I am happy that you just shared this helpful information with us.

routerlogin.com said...

We stumbled over here from a different page and thought I might as well check things out. I like what I see so now i am following you.

Netgear Router Login said...

If you want to access the Netgear Router then open the browser & type routerlogin.net & enter fill all the details & select the login button.

Nighthawk router login said...

I like the valuable information you provide in your
Articles. I will bookmark your weblog and check again here frequently.

Routerlogin.net said...

NETGEAR router login using the default login details. When the Login panel appears, it will require user data, ie. username and password.

www.routerlogin.net said...

I’m quite sure I will learn plenty of new
stuff right here! Best of luck for the next!

www.routerlogin.com said...

Hi there Dear, are you genuinely visiting
this website on a regular basis, if so then you will absolutely
get good know-how.

www.routerlogin.net said...

For Nighthawk router setup, Connect the device to the router's Wifi network. Your network name and password are shown on the screen

www.mywifiext.net Login said...

Fine with your permission let me to take hold of your RSS feed to keep up to date with imminent post. Thank you a million and please keep up the Rewarding work.

www.orbilogin.net said...

Thank you for sharing excellent information. Your site is very cool.

NDTV TODAY said...

business news in hindi

marisa said...

Ufabet is an excellent option to start. There are great rewards and customer service 24/7. Play on your phone! UFABET also offers a bonus scheme which is attractive.
ufabet
ยูฟ่า

Anonymous said...

ignou mba project
ignou mttm project
ignou mba project

ignoustudymaterial.com said...

ignou bts project
ignou assignment
ignou study material
ignou mapc project

blogger said...

Thanks For Sharing Health News In Hindi
Thanks For Sharing Lifestyle News In Hindi
Thanks For Sharing Crime News In Hindi
Thanks For Sharing Breaking News In Hindi

Ahaana jain said...

I have learned a lot from your article and I’m looking forward to applying

Internet Marketing Agency
Software Solutions Company

Ahaana jain 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

Future Of E-commerce In 2021
Keyword Research Strategy

www.routerlogin.net said...

I read this article completely regarding the resemblance of most up-to-date and earlier technologies, it’s amazing article.

orbilogin.com said...

These are in fact fantastic ideas in about blogging. You have touched some good factors here. Any way keeps up writing.

orbi firmware update failed said...

I am truly delighted to read this web site posts which includes tons of valuable data, thanks for providing such information.
orbi firmware update failed

routerloginnet said...

It’s really a great and helpful piece of information

routerlogin said...

I like the valuable information you provide in your. articles. I will bookmark your weblog and check again here frequently.

roueterlogin.net said...

I will be grateful if you continue this in future.Many people will be benefited from your writing.Cheers!

routerloginnet said...

I will be grateful if you continue this in future. Many people will be benefited from your writing.Cheers!

Mywifiext.net said...

I will be grateful if you continue this in future.Many people will be benefited from your writing. Cheers!

Mywifiext.net Setup said...

Wow, awesome blog layout! How long have you been blogging for?

orbisetuplogin.com said...

Hi there dear, are you genuinely visiting. This website on a regular basis, if so then you will absolutely

Orbilogin.com said...

I’m really impressed with your writing skills as well as with the layout on your weblog

Ahaana jain said...

Hi! I really like your content. Your post is really informative.

Customised Software
Custom Software Application Development India

Ahaana jain said...

I had no idea what a blog was or how to start one

Software Development Agency
Top Software Development Companies

Ahaana jain said...

Thanks for providing such a great article, this article is very helpful for me, a lot of thanks sir

Top Web Development Companies In India
Best Web Developing Companies

Ahaana jain 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

Custom Application Development Company
Software Development Firm

Anonymous said...

Asynchronous functions are often found in front-end applications and used particularly in independent, high-volume, IO tasks.

Know more about stamped concrete cracking

Stamped Concrete Frederick MD said...

The main distinction between synchronous and asynchronous communication is that synchronous communications involve pre-arranged, in-person, audio, or video exchanges.

Stamped Concrete Frederick MD is serving quality concrete service locally.

HVAC Heating Spokane said...

As its name suggests, C++ async is a function template fn that runs callbacks or functions or function objects asynchronously by accepting them as arguments.

Also guys you can check our HVAC Heating Spokane

Concrete Patio Harrisonburg said...

Excellent information on your site, thanks for the platform to allow us to make comments.

Concrete Patio Harrisonburg is the best concrete patio provider in town!

Spokane Countertops said...

The content is really nice, it is well written.

By the way guys you can also visit our best Spokane Countertops

Ahaana jain said...

I will definitely use this information in the very near future. I have saved this link and will return in a
How To Make An App Like Tinder
How Video Marketing Grow Your Business

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Web Design Company Toronto
Website Design Company

Beautyglaming said...

Thanks For Sharing Elf Bar
Thanks For Sharing vaperdudes

Travis john said...

Accessing the orbilogin.com web address can help you gain access to the device settings easily. This blog will effectively help users read through the process. Appreciate the post.

Jennaforbes said...

Amped wireless devices can be managed using setup.ampedwireless.com. This blog accurately explains the process and can help users understand it in easy words. Really liked the layout. Please keep posting.
setup.ampedwireless.com

Ahaana jain 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

Social Media Marketing Agency In India
Social Media Marketing Company In India

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Best Digital Marketing Company
Top Digital Marketing Companies In 2021

Yulanda Youngstrom said...

The closest private tutoring service pertains to mom's house - quality & selected private tutors in Jabodetabek ... for more information https://biologi-exed.blogspot.com/2022/06/les-privat-biologi-di-pesanggrahan.html

Ahaana jain said...

Thanks for providing such a great article, this article is very helpful for me, a lot of thanks sir

Keyword Research Strategy
Learn Graphic Designing

ABC said...

ignou mapc project
ignou bts project
mttm 16 dissertation

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Custom Software Development Toronto
Website Development Company

Beautyglaming said...

Thanks For Sharing Techradiance

Ahaana jain said...

I will definitely use this information in the very near future. I have saved this link and will return in a
Website design company
Best digital marketing companies

janvi verma said...

I have learned a lot from your article and I’m looking forward to apply

hr solutions

Technical Jobs Without Coding Skills

James said...

I liked most of the writers intent.

miami waterfront condos

«Oldest ‹Older   401 – 500 of 500   Newer› Newest»