Skip to content

Commit d45e5f8

Browse files
committed
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.
1 parent 47bf6ba commit d45e5f8

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

py/moduerrno.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,13 @@ const mp_obj_module_t mp_module_uerrno = {
8989
.globals = (mp_obj_dict_t*)&mp_module_uerrno_globals,
9090
};
9191

92+
mp_obj_t mp_errno_to_str(mp_obj_t errno_val) {
93+
mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP);
94+
if (elem == NULL) {
95+
return errno_val;
96+
} else {
97+
return elem->value;
98+
}
99+
}
100+
92101
#endif //MICROPY_PY_UERRNO

py/mperrno.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,10 @@
134134

135135
#endif
136136

137+
#if MICROPY_PY_UERRNO
138+
mp_obj_t mp_errno_to_str(mp_obj_t errno_val);
139+
#else
140+
static inline mp_obj_t mp_errno_to_str(mp_obj_t errno_val) { return errno_val; }
141+
#endif
142+
137143
#endif // __MICROPY_INCLUDED_PY_MPERRNO_H__

py/objexcept.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
#include "py/objtype.h"
3737
#include "py/runtime.h"
3838
#include "py/gc.h"
39+
#include "py/mperrno.h"
3940

4041
// Instance of MemoryError exception - needed by mp_malloc_fail
4142
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) {
288289

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

0 commit comments

Comments
 (0)