diff --git a/components/esp_common/include/esp_err.h b/components/esp_common/include/esp_err.h index 58026d02e693..0b4210985303 100644 --- a/components/esp_common/include/esp_err.h +++ b/components/esp_common/include/esp_err.h @@ -92,6 +92,29 @@ void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int l #endif /** @endcond */ +/** + * Macro that returns the error code if an error occurs, optionally running extra code. + * The extra code can be placed after the function thay may error and it will only run if the error occurs. + * + * @example + * esp_err_t my_function() + * { + * // Let's say `read_file()` returns esp_err_t and we want to `close_file()` on error. + * ESP_ERROR_CHECK_RETURN(read_file(), close_file()) + * // If the code page gets here, `read_file()` succeeded. + * process_file(); + * close_file(); + * return ESP_OK; + * } + */ +#define ESP_ERROR_CHECK_RETURN(x, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + __VA_ARGS__; \ + return err_rc_; \ + } \ + } while (0) + /** * Macro which can be used to check the error code, * and terminate the program in case the code is not ESP_OK.