libcruft-util/cruft/util/posix/except.cpp

144 lines
2.9 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2010-2018
* Danny Robson <danny@nerdcruft.net>
*/
#include "except.hpp"
#include "../platform.hpp"
#include "../debug/assert.hpp"
#include <cstring>
using cruft::posix::error;
///////////////////////////////////////////////////////////////////////////////
/// Construct an exception object from a given error value.
///
/// The error value MUST be an error at construction time.
error::error (int _code):
m_code (_code)
{
CHECK_NEQ (_code, 0);
}
///----------------------------------------------------------------------------
/// Construct an exception object from the current value of errno.
///
/// errno MUST signal an error at construction time.
error::error ():
error (last_code ())
{
CHECK_NEQ (m_code, 0);
}
///////////////////////////////////////////////////////////////////////////////
int
error::last_code (void)
{
return errno;
}
//-----------------------------------------------------------------------------
int
error::code (void) const
{
return m_code;
}
///////////////////////////////////////////////////////////////////////////////
/// Throw an exception object if errno currently signals an error.
void
error::try_code (void)
{
try_code (last_code ());
}
///----------------------------------------------------------------------------
/// Throw an exception object if 'code' represents an error.
void
error::try_code (int code)
{
if (__builtin_expect (code != 0, false))
throw error (code);
}
///----------------------------------------------------------------------------
void
error::throw_code (void)
{
throw_code (last_code ());
}
///----------------------------------------------------------------------------
void
error::throw_code (int code)
{
CHECK_NEQ (code, 0);
throw error (code);
}
///////////////////////////////////////////////////////////////////////////////
const char*
error::what (void) const noexcept
{
return strerror (m_code);
}
///////////////////////////////////////////////////////////////////////////////
using cruft::posix::eai;
#if !defined(PLATFORM_WIN32)
#include <netdb.h>
#else
#include <ws2tcpip.h>
#endif
//-----------------------------------------------------------------------------
eai::eai (int code):
runtime_error (gai_strerror (code)),
m_code (code)
{ ; }
//-----------------------------------------------------------------------------
int
eai::code (void) const
{
return m_code;
}
//-----------------------------------------------------------------------------
void
eai::try_code (int code)
{
if (code)
throw_code (code);
}
//-----------------------------------------------------------------------------
void
eai::throw_code (int code)
{
throw eai { code };
}