py: Add mp_errno_to_str() and use it to provide nicer OSError msgs.

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.
This commit is contained in:
Damien George 2016-05-12 13:20:40 +01:00
parent 47bf6ba61a
commit d45e5f8c35
3 changed files with 20 additions and 0 deletions

View File

@ -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

View File

@ -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__

View File

@ -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};
@ -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);
}