Skip to content

Commit

Permalink
py: Add mp_errno_to_str() and use it to provide nicer OSError msgs.
Browse files Browse the repository at this point in the history
If an OSError is raised with an integer argument, and that integer
corresponds to an errno, then the string for the errno is used as the
argument to the exception, instead of the integer.  Only works if
the uerrno module is enabled.
  • Loading branch information
dpgeorge committed May 12, 2016
1 parent 47bf6ba commit d45e5f8
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions py/moduerrno.c
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,13 @@ const mp_obj_module_t mp_module_uerrno = {
.globals = (mp_obj_dict_t*)&mp_module_uerrno_globals,
};

mp_obj_t mp_errno_to_str(mp_obj_t errno_val) {
mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP);
if (elem == NULL) {
return errno_val;
} else {
return elem->value;
}
}

#endif //MICROPY_PY_UERRNO
6 changes: 6 additions & 0 deletions py/mperrno.h
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,10 @@

#endif

#if MICROPY_PY_UERRNO
mp_obj_t mp_errno_to_str(mp_obj_t errno_val);
#else
static inline mp_obj_t mp_errno_to_str(mp_obj_t errno_val) { return errno_val; }
#endif

#endif // __MICROPY_INCLUDED_PY_MPERRNO_H__
5 changes: 5 additions & 0 deletions py/objexcept.c
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#include "py/objtype.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/mperrno.h"

// Instance of MemoryError exception - needed by mp_malloc_fail
const mp_obj_exception_t mp_const_MemoryError_obj = {{&mp_type_MemoryError}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
Expand Down Expand Up @@ -288,6 +289,10 @@ mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {

// "Optimized" version for common(?) case of having 1 exception arg
mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
// try to provide a nice string instead of numeric value for errno's
if (exc_type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(arg)) {
arg = mp_errno_to_str(arg);
}
return mp_obj_new_exception_args(exc_type, 1, &arg);
}

Expand Down

0 comments on commit d45e5f8

Please sign in to comment.