Improved error handling

This commit is contained in:
BLM 2015-07-16 13:25:44 -05:00
parent d14ab5d435
commit 69c0f0f4fc
1 changed files with 38 additions and 31 deletions

View File

@ -35,7 +35,14 @@ void reportGenericError(std::exception& exception) {
errdetail("%s", exception.what()))); errdetail("%s", exception.what())));
} }
void logInfo(const char* msg) {
ereport(INFO,
(errcode(ERRCODE_SUCCESSFUL_COMPLETION),
errmsg("%s", msg)));
}
//TODO: handle non-exception thrown types? (shouldn't happen, but you never know...) //TODO: handle non-exception thrown types? (shouldn't happen, but you never know...)
//TODO: check null args? (PG_ARGISNULL) Make non-strict?
extern "C" { extern "C" {
#ifdef PG_MODULE_MAGIC #ifdef PG_MODULE_MAGIC
@ -48,6 +55,7 @@ extern "C" {
Datum Datum
phone_number_in(PG_FUNCTION_ARGS) phone_number_in(PG_FUNCTION_ARGS)
{ {
try {
const char *str = PG_GETARG_CSTRING(0); const char *str = PG_GETARG_CSTRING(0);
PhoneNumber *number; PhoneNumber *number;
@ -57,8 +65,8 @@ extern "C" {
reportOutOfMemory(); reportOutOfMemory();
PG_RETURN_NULL(); PG_RETURN_NULL();
} }
new(number) PhoneNumber();
try {
using PNU = i18n::phonenumbers::PhoneNumberUtil; using PNU = i18n::phonenumbers::PhoneNumberUtil;
PNU::ErrorType error; PNU::ErrorType error;
error = phoneUtil->Parse(str, "US", number); error = phoneUtil->Parse(str, "US", number);
@ -95,24 +103,16 @@ extern "C" {
Datum Datum
phone_number_out(PG_FUNCTION_ARGS) phone_number_out(PG_FUNCTION_ARGS)
{ {
PhoneNumber *number = (PhoneNumber*)PG_GETARG_POINTER(0); try {
const PhoneNumber *number = (PhoneNumber*)PG_GETARG_POINTER(0);
std::string formatted; std::string formatted;
char *result; char *result;
try {
phoneUtil->Format(*number, PhoneNumberUtil::INTERNATIONAL, &formatted); phoneUtil->Format(*number, PhoneNumberUtil::INTERNATIONAL, &formatted);
} catch(std::bad_alloc& e) {
reportOutOfMemory();
} catch (std::exception& e) {
reportGenericError(e);
}
//Copy the formatted number to a C-style string. //Copy the formatted number to a C-style string.
//We must use the PostgreSQL allocator, not new/malloc. //We must use the PostgreSQL allocator, not new/malloc.
size_t len = formatted.length(); size_t len = formatted.length();
ereport(INFO,
(errcode(ERRCODE_SUCCESSFUL_COMPLETION),
errmsg("Length: %zu", len)));
result = (char*)palloc(len + 1); result = (char*)palloc(len + 1);
if(result == nullptr) { if(result == nullptr) {
reportOutOfMemory(); reportOutOfMemory();
@ -122,10 +122,17 @@ extern "C" {
result[len] = '\0'; result[len] = '\0';
PG_RETURN_CSTRING(result); PG_RETURN_CSTRING(result);
} catch(std::bad_alloc& e) {
reportOutOfMemory();
} catch (std::exception& e) {
reportGenericError(e);
}
PG_RETURN_NULL();
} }
PGDLLEXPORT PG_FUNCTION_INFO_V1(phone_number_recv); PGDLLEXPORT PG_FUNCTION_INFO_V1(phone_number_recv);
//TODO: handle leading zeroes?
PGDLLEXPORT PGDLLEXPORT
Datum Datum
phone_number_recv(PG_FUNCTION_ARGS) phone_number_recv(PG_FUNCTION_ARGS)